简体   繁体   English

获取带有名称的DataTable列的索引

[英]get index of DataTable column with name

I have some code which sets the value of cells in a DataRow by column name ie 我有一些代码通过列名设置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;

ie 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? 即,我是否需要在最初创建表时创建某种列索引和列名称的字典,或者我可以稍后从列名称中获取索引而不执行此操作?

You can use DataColumn.Ordinal to get the index of the column in the DataTable . 您可以使用DataColumn.Ordinal来获取DataTable列的索引。 So if you need the next column as mentioned use Column.Ordinal + 1 : 因此,如果您需要提到的下一列,请使用Column.Ordinal + 1

row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;

试试这个:

int index = row.Table.Columns["ColumnName"].Ordinal;

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;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM