获取名称为DataTable列的索引 [英] get index of DataTable column with name

查看:969
本文介绍了获取名称为DataTable列的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码,通过列名设置DataRow中的单元格的值,即

  row [ColumnName] = someValue; 

我还要在列中立即右边的列中设置此行的值以上。显然,如果我通过索引获取单元格,而不是通过列名称,这将很容易。那么有一种从列名获取列索引的方法,让我可以这样做:

  row [index + 1] = someOtherValue; 

ie。当表最初创建时,是否需要创建一些列索引和列名称的字典,或者我可以稍后从列名中获取索引吗?

解决方案

您可以使用 DataColumn.Ordinal 以获取 DataTable 中的列的索引。所以如果你需要下面的列,请使用 Column.Ordinal + 1

  row [row.Table.Columns [ColumnName]。Ordinal + 1] = someOtherValue; 


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 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆