Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get index of DataTable column with name

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?

like image 853
Andy Avatar asked Jul 05 '12 08:07

Andy


People also ask

How to get column index by column name in DataTable?

Select("ColumnName = ColumnValue"). FirstOrDefault(); int index = dt. Rows.

How to get column index in DataTable?

function column(). Get the column index of the selected column. Specify if you want to get the column data index (default) or the visible index ( visible ). The column index for the selected column.

How do I get the index of a column from a DataFrame?

You can get the column index from the column name in Pandas using DataFrame. columns. get_loc() method.

How to find index of column in c#?

IndexOf(String) Gets the index of the column with the specific name (the name is not case sensitive).


1 Answers

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.

like image 181
Tim Schmelter Avatar answered Sep 29 '22 21:09

Tim Schmelter