开发者

How to Assign a datarow object in .NET 1.1

currently I am doing this...

object s = new object();
s = mydatarow["mycolumn"];

What I would like to do is...

DataRow r = null;
r = mydatarow["m开发者_如何学Cycolumn"];

and I get an error saying that can not covert from object to DataRow.

is there a better way of doing this?


What you're currently doing...

object s = new object();
s = mydatarow["mycolumn"];

This isn't a good idea, because the first line creates a new object, and then the second line throws away that object and replaces it with the value from the "mycolumn" column in the DataRow. This doesn't really hurt much, except that it creates extra work for the garbage collector for no good reason. Instead of that, you should do this:

object s = mydatarow["mycolumn"];

However, if you happen to know that "mycolumn" contains a string value, you can instead do this:

string s = (string)mydatarow["mycolumn"];

Likewise, if "mycolumn" is an integer column...

int x = (int)mydatarow["mycolumn"];

Under no circumstances should you do the following, because it simply doesn't make any sense, and the framework is nice enough to tell you that the "mycolumn" value in your DataRow is not, in fact, another DataRow.

DataRow r = null;
r = mydatarow["mycolumn"];


looks like you do something wrong.

DataRow r = null;
r = mydatarow["mycolumn"];

mydatarow is DataRow itself. when you reference to specific column you get "cell" of the table. (it has type object, because DataSets basically are loosely typed) but you try to assign cell to DataRow.

got it?


There are three things... a DataTable (multiple rows), a data ROW (multiple fields/columns) of a TABLE, and the individual column cells themselves.

DataTable oTbl = ResultSetFromYourQuery();
DataRow oDR = oTbl.Rows[0];  // Rows[0] is first row in a result table (zero-based)
String ColumnValue = oDR["YourColumnName"];


You can try this:

DataRow r = null;
r = (DataRow) mydatarow["mycolumn"]; //*

It is unlikely, but theoretically possible, that this will work. Usually when I'm having trouble with this stuff I'll stick in a breakpoint (where I added //*), watch mydatarow["mycolumn"], and have Visual Studio tell me what type it actually is (among other things to determine).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜