开发者

Convert datarow to int

I have a datarow, but how can i convert it to an int ?

I tried this, but it doesn't work.

dsMovie = (DataSet)wsMovie.getKlantId();
    开发者_如何学JAVA        tabel = dsMovie.Tables["tbl_klanten"];
            eersteRij = tabel.Rows[0];
(Int32.Parse(eersteRij.ToString())


A DataRow is an object; it is not an integer. A DataRow contains one or more columns of data. You can index into the DataRow to access the values of these coulmns.

If table tbl_klanten contains one column, and that column is an integer, you can do the following:

var myInt = (int)eersteRij[0];

if the column is a string containing the value of an integer,

var myInt = int.Parse(eersteRij[0]);

If the column is named klant_id...

var myInt = (int)eersteRij["klant_id"];

if the column is a string containing the value of an integer,

var myInt = int.Parse(eersteRij["klant_id"]);


Simply use the Field method:

int result = row.Field<int>("ColName");

The Field method also supports nullable types:

The Field method provides support for accessing columns as nullable types. If the underlying value in the DataSet is Value, the returned nullable type will have a value of null.

And please notice:

The Field method does not perform type conversions. If type conversion is required, you should first obtain the column value by using the Field method. The column value should then be converted to another type.


Because even at that level of hierarchy you still have a DataRow and you can't convert a DataRow to int.. a value could be converted though.

And why are you converting whole DataRow to int.. usually you would like to get a value in a cell at a row so try, Somthing like this:

int value = (int)eersteRij.Items[0];

where 0 can be replaced by the cell position(int) or Column name(string)


You'll need to know which index the object you want is on, and cast that to an int, e.g.:

int value = (int)eersteRij[0];


DataSet dataSet = getDataFromDatabase();
DataRow tableRow = dataSet.Tables[0].Rows[0];

int valueAsInteger = Convert.ToInt32(tableRow["COLUMN_NAME"]);


I tend to use IndexOf() when looping thru the dataTable.

foreach (DataRow row in DataTable.table.Rows) { int index = dataTable.Rows.IndexOf(row); }

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜