AJ152
AJ152

Reputation: 685

If rows exists before adding it to datagridview

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

Error 2 A local variable named 'row' cannot be declared in this scope because it would give a different meaning to 'row', which is already used in a 'parent or current' scope to denote something else 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[] 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);
    }


}

Upvotes: 0

Views: 2756

Answers (1)

ASh
ASh

Reputation: 35646

row is a name for string[] and for loop variable. rename one of them

DataGridView dgData isn't enumerable, iterate over dgData.Rows in 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);
    }
}

Upvotes: 1

Related Questions