DataRow:通过给定的列名选择单元格值 [英] DataRow: Select cell value by a given column name

查看:688
本文介绍了DataRow:通过给定的列名选择单元格值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



使用OleDbConnection从Excel电子表格中读取数据行。



如果我尝试使用列名从DataRow中选择数据,即使有数据,也返回DBNull。



但是这不是那么简单。



datarow.Table.Columns [5] .ColumnName 返回我的列 。

datarow [我的列] 返回DBNull。

datarow [5] code>返回500.

datarow [datarow.Table.Columns [5] .ColumnName] 返回DBNull。 (只是为了确保它不是一个错字!)



我可以使用列号从数据库中选择东西,但我不喜欢这样做,因为列排序改变,该软件将中断。

解决方案

您正在使用哪个版本的.NET?自.NET 3.5以来,有一个程序集System.Data.DataSetExtensions,它包含dataTables,dataRows等各种有用的扩展。



你可以尝试使用

  row.Field< type>(fieldName); 

如果不起作用,可以这样做:

  DataTable table = new DataTable(); 
var myColumn = table.Columns.Cast< DataColumn>()。SingleOrDefault(col => col.ColumnName ==myColumnName);
if(myColumn!= null)
{
//只是一些roww
var tableRow = table.AsEnumerable()。
var myData = tableRow.Field< string>(myColumn);
//或如果以上不起作用
myData = tableRow.Field< string>(table.Columns.IndexOf(myColumn));
}


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.

解决方案

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));
}

这篇关于DataRow:通过给定的列名选择单元格值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆