get index of DataTable column with name

后端 未结 4 1866
遇见更好的自我
遇见更好的自我 2020-12-13 23:58

I have some code which sets the value of cells in a DataRow by column name i.e.

row[\"ColumnName\"] = someValue;

I want to also set the val

相关标签:
4条回答
  • 2020-12-14 00:37

    Try this:

    int index = row.Table.Columns["ColumnName"].Ordinal;
    
    0 讨论(0)
  • 2020-12-14 00:39

    You can use DataColumn.Ordinal to get the index of the column in the DataTable. So if you need the next column as mentioned use Column.Ordinal + 1:

    row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;
    
    0 讨论(0)
  • 2020-12-14 00:47

    I wrote an extension method of DataRow which gets me the object via the column name.

    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);
    }
    
    0 讨论(0)
  • 2020-12-14 00:51

    You can simply use 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;
    
    0 讨论(0)
提交回复
热议问题