0
我無法使此代碼正常工作,我正在從SQL(WHILE)查詢中將行添加到datagridview,但在執行此操作時需要運行一個foreach裏面來檢查row.Cells [0] .value的添加它之前存在,但我發現了以下錯誤:在將數據添加到datagridview之前檢查行是否存在
錯誤1 foreach語句無法在類型「System.Windows變量的操作。 Forms.DataGridView',因爲'System.Windows.Forms.DataGridView'不包含'GetEnumerator'的公共定義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[] row1 = 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(row1);
}
}
奏效,謝謝! – AJ152