C# 获取带有名称的 DataTable 列的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11340264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get index of DataTable column with name
提问by Andy
I have some code which sets the value of cells in a DataRow by column name i.e.
我有一些代码可以通过列名设置 DataRow 中单元格的值,即
row["ColumnName"] = someValue;
I want to also set the value for this row in the column immediately to the right of the one found above. Clearly if I was getting the cell by index rather than by column name this would be easy. So is there a way of getting the column index from the column name thus allowing me to do:
我还想立即在上面找到的列的右侧设置该行的值。显然,如果我按索引而不是按列名获取单元格,这将很容易。那么有没有办法从列名中获取列索引,从而允许我这样做:
row[index + 1] = someOtherValue;
i.e. do I need create some kind of dictionary of column index and column names when the table is initially created, or can I get the index from the column name later on without doing this?
即我是否需要在最初创建表时创建某种列索引和列名字典,或者我可以稍后从列名中获取索引而不这样做吗?
采纳答案by Tim Schmelter
You can use DataColumn.Ordinalto get the index of the column in the DataTable. So if you need the next column as mentioned use Column.Ordinal + 1:
您可以使用DataColumn.Ordinal来获取DataTable. 因此,如果您需要前面提到的下一列,请使用Column.Ordinal + 1:
row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;
回答by Kell
Try this:
尝试这个:
int index = row.Table.Columns["ColumnName"].Ordinal;
回答by Tom Beech
I wrote an extension method of DataRow which gets me the object via the column name.
我写了一个 DataRow 的扩展方法,它通过列名获取对象。
public static object Column(this DataRow source, string columnName)
{
var c = source.Table.Columns[columnName];
if (c != null)
{
return source.ItemArray[c.Ordinal];
}
throw new ObjectNotFoundException(string.Format("The column '{0}' was not found in this table", columnName));
}
And its called like this:
它的名字是这样的:
DataTable data = LoadDataTable();
foreach (DataRow row in data.Rows)
{
var obj = row.Column("YourColumnName");
Console.WriteLine(obj);
}
回答by ebram khalil
You can simply use DataColumnCollection.IndexOf
您可以简单地使用DataColumnCollection.IndexOf
So that you can get the index of the required column by name then use it with your row:
这样您就可以按名称获取所需列的索引,然后将其与您的行一起使用:
row[dt.Columns.IndexOf("ColumnName")] = columnValue;

