将datagrid的值与从数据库中选择的值进行比较

时间:2014-05-24 14:05:40

标签: datagridview compare sqldatareader

我用excel数据填充网格,想要比较数据库中是否存在值?

for (int i = 0; i < dataGridView1.RowCount; i++)
        {
            if (radioButton1.Checked == true)
            {
                string strConn = @"Data Source='" + dbconfig.tb1 + "';Initial Catalog='" + dbconfig.tb2 + "';user='" + dbconfig.tb3 + "';pwd='" + dbconfig.tb4 + "'";
                SqlConnection conn = new SqlConnection(strConn);
                conn.Open();
                SqlCommand cmd = new SqlCommand("SELECT CODE FROM LG_" + dbconfig.tb5 + "_TABLE WHERE CODE NOT LIKE '" + dataGridView1.Rows[i].Cells[0].Value + "'", conn);
                cmd.ExecuteNonQuery();
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    MessageBox.Show("Check ITEMS" + reader[i].ToString());
                }
                conn.Close();
            }
        }

1 个答案:

答案 0 :(得分:0)

如果我理解你的话,你想检查数据库中是否存在来自你的网格中的某些值的记录,我建议你使用ExecuteScalar方法:

SqlCommand cmd = new SqlCommand(SELECT COUNT (Code) FROM Table WHERE .....);
var res = command.ExecuteScalar();

                    if ((int)res > 0)
                        //Record exists
                    else
                        //record does not exists