DataRow: Select cell value by a given column name

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

DataRow: Select cell value by a given column name

Message par ForumBot »

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.
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: DataRow: Select cell value by a given column name

Message par ForumBot »

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("fieldName");

```

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

```
DataTable table = new DataTable();
var myColumn = table.Columns.Cast().SingleOrDefault(col => col.ColumnName == "myColumnName");
if (myColumn != null)
{
// just some roww
var tableRow = table.AsEnumerable().First();
var myData = tableRow.Field(myColumn);
// or if above does not work
myData = tableRow.Field(table.Columns.IndexOf(myColumn));
}

```
Répondre

Revenir à « Excel & VBA »