49

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 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?

Andy
  • 7,646
  • 8
  • 46
  • 69

4 Answers4

89

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;

Warning:

This code returns the next column, so the one after ColumnName, as requested in the question.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
42

Try this:

int index = row.Table.Columns["ColumnName"].Ordinal;
Kell
  • 3,252
  • 20
  • 19
9

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;
ebram khalil
  • 8,252
  • 7
  • 42
  • 60
3

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);
}
Tom Beech
  • 2,289
  • 1
  • 21
  • 25
  • Should this extension throw "ObjectNotFoundException" instead of "ItemNotFoundException"?? http://msdn.microsoft.com/en-us/library/system.data.objectnotfoundexception%28v=vs.110%29.aspx – Jonathan Kittell Jan 09 '15 at 13:58
  • -1 DataRow has that already built in your example if you did row["YourColumnName"] it will return the content of that cell. If the column doesn't exist it throws System.ArguementException and this is the message {"Column 'YourColumnName' does not belong to table Table."} So unless this has some performance gain please delete. Also this doesn't answer the question of how to get the index. – DeadlyChambers May 25 '15 at 11:39