I'm having trouble getting this code to work, I'm adding rows to a datagridview from an SQL (WHILE) query, but while doing that I need to run a foreach inside to check if a row.Cells[0].Value exists before adding it, but i'm getting the following errors:
Error 1 foreach statement cannot operate on variables of type 'System.Windows.Forms.DataGridView' because 'System.Windows.Forms.DataGridView' does not contain a public definition for 'GetEnumerator' C:\Users................project1.cs
Here is my code:
//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);
}
}