c# – 如何通过列名称获取DataGridView的单元格值?
发布时间:2020-12-15 04:05:23 所属栏目:百科 来源:网络整理
导读:我有一个带有DataGridView的WinForms应用程序,DataSource是一个DataTable(从SQL Server填充),它的列有一个xxx.以下代码引发了“ArgumentException”未被处理的异常.不能找到名为xxx的列. foreach (DataGridViewRow row in Rows){ if (object.Equals(row.Cell
我有一个带有DataGridView的WinForms应用程序,DataSource是一个DataTable(从SQL Server填充),它的列有一个xxx.以下代码引发了“ArgumentException”未被处理的异常.不能找到名为xxx的列.
foreach (DataGridViewRow row in Rows) { if (object.Equals(row.Cells["xxx"].Value,123)) 可以通过列名称获取单元格值吗? 解决方法
DataGridViewColumn对象具有一个名称(仅在表单设计器中显示)和一个HeaderText(在列顶部的GUI中显示)属性.您的示例中的索引器使用列的Name属性,因此,因为您说这不工作,我假设您真的试图使用列的标题.
没有什么内置的,做你想要的,但它很容易添加.我会使用扩展方法使其易于使用: 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.GetCellFromColumnHeader("xxx").Value,123)) { // ... } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |