我无法使此代码生效,我在SQL( WHILE )查询中向datagridview添加行,但在执行此操作时,我需要运行foreach在里面检查是否存在 row.Cells [0] .Value ,然后再添加它,但我收到以下错误:
错误1 foreach语句无法对类型为' System.Windows.Forms.DataGridView'的变量进行操作。因为' System.Windows.Forms.DataGridView'不包含' GetEnumerator'的公开定义C:\用户................ project1.cs
错误2名为' row'的局部变量不能在此范围内声明,因为它会给“行”提供不同的含义,这已经在“父母”或“当前”中使用过。范围表示别的东西C:\ Users ................ project1.cs
这是我的代码:
//dgData is a datagridview with columns created programmatically, this works already by the way.
dgData.ColumnCount = 3;
dgData.Columns[0].Name = "ColumnA";
dgData.Columns[0].Name = "ColumnB";
dgData.Columns[0].Name = "ColumnC";
string query1 = " SELECT * FROM ....... ";
SqlCommand cmd1 = new SqlCommand(query1, connection);
//Create a data reader and Execute the command
SqlDataReader dataReader1 = cmd1.ExecuteReader();
Application.DoEvents();
while (dataReader1.Read())
{
string[] row = new string[] { dataReader1["columnA"].ToString(), dataReader1["columnB"].ToString(), dataReader1["columnC"].ToString() };
Boolean found = false;
// this foreach is what doesn't work.
foreach (DataGridViewRow row in dgData)
{
if (row.Cells[0].Value == dataReader1["columnA"].ToString())
{
// row exists
found = true;
MessageBox.Show("Row already exists");
}
}
if (!found)
{
dgData.Rows.Add(row);
}
}
答案 0 :(得分:1)
row
是string[]
和循环变量的名称。重命名其中一个
DataGridView dgData不可枚举,在dgData.Rows
foreach
while (dataReader1.Read())
{
string[] newRow = new string[]
{
dataReader1["columnA"].ToString(),
dataReader1["columnB"].ToString(),
dataReader1["columnC"].ToString()
};
Boolean found = false;
foreach (DataGridViewRow row in dgData.Rows)
{
if (row.Cells[0].Value == dataReader1["columnA"].ToString())
{
// row exists
found = true;
MessageBox.Show("Row already exists");
break;
}
}
if (!found)
{
dgData.Rows.Add(newRow);
}
}