获取带有名称的 DataTable 列的索引 [英] get index of DataTable column with name
问题描述
我有一些代码可以按列名设置 DataRow 中单元格的值,即
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?
推荐答案
您可以使用 DataColumn.Ordinal
获取DataTable
中列的索引.因此,如果您需要前面提到的下一列,请使用 Column.Ordinal + 1
:
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;
这篇关于获取带有名称的 DataTable 列的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!