0

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);
    }


}

1 Answer 1

1

I'm not shure, but could it be that you have to use

foreach (DataGridViewRow row in dgData.Rows)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.