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?
You can use
DataColumn.Ordinal
to get the index of the column in theDataTable
. So if you need the next column as mentioned useColumn.Ordinal + 1
:Try this:
I wrote an extension method of DataRow which gets me the object via the column name.
And its called like this:
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: