Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataRow: Select cell value by a given column name

I have a problem with a DataRow that I'm really struggling with.

The datarow is read in from an Excel spreadsheet using an OleDbConnection.

If I try to select data from the DataRow using the column name, it returns DBNull even though there is data there.

But it's not quite that simple.

datarow.Table.Columns[5].ColumnName returns "my column".
datarow["my column"] returns DBNull.
datarow[5] returns 500.
datarow[datarow.Table.Columns[5].ColumnName] returns DBNull. (just to make sure its not a typo!)

I could just select things from the datarow using the column number, but I dislike doing that since if the column ordering changes, the software will break.

like image 311
VaticanUK Avatar asked Aug 19 '11 10:08

VaticanUK


People also ask

Which activity can be used to retrieve the value from a specific column from a DataRow object?

ColumnIndex - The index of the column whose value is to be retrieved from the DataRow.

How do I find my DataRow column name?

You can get the column names from DataRow by using (datarow). Table. Columns and this will return “DataColumnCollection”.

How do you value a DataRow?

Just use an index to access each element. The following code would acccess the first element in the list. the name of the property you are trying to access. each datarow will maintain the schema of the datatable that it came from so you still have columns in the datarow.

What is DataRow C#?

A DataRow represent a row of data in data table. You add data to the data table using DataRow object. A DataRowCollection object represents a collection of data rows of a data table.


2 Answers

Which version of .NET are you using? Since .NET 3.5, there's an assembly System.Data.DataSetExtensions, which contains various useful extensions for dataTables, dataRows and the like.

You can try using

row.Field<type>("fieldName"); 

if that doesn't work, you can do this:

DataTable table = new DataTable(); var myColumn = table.Columns.Cast<DataColumn>().SingleOrDefault(col => col.ColumnName == "myColumnName"); if (myColumn != null) {     // just some roww     var tableRow = table.AsEnumerable().First();     var myData = tableRow.Field<string>(myColumn);     // or if above does not work     myData = tableRow.Field<string>(table.Columns.IndexOf(myColumn)); } 
like image 183
Hassan Avatar answered Oct 07 '22 23:10

Hassan


This must be a new feature or something, otherwise I'm not sure why it hasn't been mentioned.

You can access the value in a column in a DataRow object using row["ColumnName"]:

DataRow row = table.Rows[0]; string rowValue = row["ColumnName"].ToString(); 
like image 38
Jimmy Avatar answered Oct 07 '22 22:10

Jimmy