get index of DataTable column with name

后端 未结 4 1867
遇见更好的自我
遇见更好的自我 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: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);
    }
    

提交回复
热议问题