我有一个WinForms应用程序,其中一个DataGridView
的数据源是从SQL Server填充的DataTable
,其中有一个名为xxx
的列。 下面的代码会引发以下异常:
未处理的ArgumentException异常。找不到名为xxx的列。
foreach (DataGridViewRow row in Rows)
{
if (object.Equals(row.Cells["xxx"].Value, 123))
}
是否可以通过列名获取单元格的值?
我有一个WinForms应用程序,其中一个DataGridView
的数据源是从SQL Server填充的DataTable
,其中有一个名为xxx
的列。 下面的代码会引发以下异常:
未处理的ArgumentException异常。找不到名为xxx的列。
foreach (DataGridViewRow row in Rows)
{
if (object.Equals(row.Cells["xxx"].Value, 123))
}
是否可以通过列名获取单元格的值?
DataGridViewColumn
对象有一个Name
属性(仅在表单设计器中显示)和一个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.GetCellValueFromColumnHeader("xxx"), 123))
{
// ...
}
}
xxx
索引并使用,对吧? - Katia通过这样做,您将能够访问当前选择行中“xxx”列名称的单元格。
dataGridView1.SelectedRows[0].Cells["xxx"]
是的,只需删除引号并添加 .Index,即:
foreach (DataGridViewRow row in Rows)
{
if (object.Equals(row.Cells[xxx.Index].Value, 123))
......如果您的列真的称为 xxx,而不是像 Column1 等其他名称。您可以独立设置列名和列标题,请在设计器中检查。
if(dataGridViewProjectList.Rows[dataGridViewProjectList.CurrentCell.RowIndex].Cells["dateendDataGridViewTextBoxColumn"].Value.ToString().Length == 0)
如果您在设计模式下对网格列进行操作, 那么列名将是gridView~~~Column控件的名称 例如:
DataGridViewTextBoxColumn idDataGridViewTextBoxColumn = new DataGridViewTextBoxColumn();
idDataGridViewTextBoxColumn.Name = "idDataGridViewTextBoxColumn";
row.Cells["idDataGridViewTextBoxColumn"].Value
If you look about :
row.Cells["xxx"].Value;
这是最初的回答:
row.Cells[yourdataGridView.Columns["xxx"].Index].Value;
TxtTankPainting.Text = DataGridTransfData.Rows[e.RowIndex].Cells["TankPainting"].Value.ToString();
TxtTankPosition.Text = DataGridTransfData.Rows[e.RowIndex].Cells["TankPosition"].Value.ToString();
TxtCorePosition.Text = DataGridTransfData.Rows[e.RowIndex].Cells["CorePosition"].Value.ToString();
dataGridView2.Columns[1].HeaderText = "Invoice No";
dataGridView2.Columns[1].Name = "invoice_no";
然后可以像这样使用该名称作为索引:
foreach (DataGridViewRow row in rows_with_checked_column)
{
MessageBox.Show(row.Cells["invoice_no"].Value.ToString());
}