在将行添加到datagridview之前检查行是否存在

时间:2017-06-04 18:19:58

标签: c# sql datagridview

我无法使用此代码,我正在从SQL( WHILE )查询中向datagridview添加行,但在执行此操作时,我需要在内部运行foreach来检查如果在添加之前存在 row.Cells [0] .Value ,但我收到以下错误:

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


}

1 个答案:

答案 0 :(得分:1)

我不是害羞,但可能是你必须使用

foreach (DataGridViewRow row in dgData.Rows)