如何通过列名获取DataGridView的单元格值? [英] How to get cell value of DataGridView by column name?
问题描述
我有一个带有 DataGridView
的WinForms应用程序,该数据源是一个数据表(由SQL Server填充),其列为 xxx
。以下代码引发了
I have a WinForms application with a DataGridView
, which DataSource is a DataTable (filled from SQL Server) which has a column of xxx
. The following code raises the exception of
ArgumentException未处理的异常。找不到名为xxx的列。
ArgumentException was unhandled. Column named xxx cannot be found.
foreach (DataGridViewRow row in Rows)
{
if (object.Equals(row.Cells["xxx"].Value, 123))
}
是否可以通过列名获取单元格值?
Is it possible to get the cell values by column name?
推荐答案
DataGridViewColumn
对象具有 Name
(仅在表单设计器中显示)和 HeaderText
(在列顶部的GUI中显示)属性。您示例中的索引器使用列的 Name
属性,因此,既然您说这行不通,我认为您确实在尝试使用列的标题。
DataGridViewColumn
objects have a Name
(shown only in the forms designer) and a HeaderText
(shown in the GUI at the top of the column) property. The indexer in your example uses the column's Name
property, so since you say that isn't working I assume you're really trying to use the column's header.
没有内置功能可以满足您的需求,但是添加起来很容易。我将使用扩展方法使其易于使用:
There isn't anything built in that does what you want, but it's easy enough to add. I'd use an extension method to make it easy to use:
public static class DataGridHelper
{
public static object GetCellValueFromColumnHeader(this DataGridViewCellCollection CellCollection, string HeaderText)
{
return CellCollection.Cast<DataGridViewCell>().First(c => c.OwningColumn.HeaderText == HeaderText).Value;
}
}
然后在您的代码中:
foreach (DataGridViewRow row in Rows)
{
if (object.Equals(row.Cells.GetCellValueFromColumnHeader("xxx"), 123))
{
// ...
}
}
这篇关于如何通过列名获取DataGridView的单元格值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!