使用datagridview避免数据库中的重复值以避免它。

问题描述:

如果我输入已经输入的已经存在的品种代码消息框应该显示消息。

我试过这段代码但没有用,请帮助我。

If I enter already entered a already existing variety code message box should show the message.
I tried this code but not worked please help me.

if (dataGridViewpro.CurrentCell.ColumnIndex == 4)
{
    if (con.State != ConnectionState.Open)
    {
        con.Open();
    }
    OleDbCommand cmdcheckcodeexit = new OleDbCommand("SELECT varietycode FROM product where varietycode='" + dataGridViewpro.Rows[4].Cells["varietycode"].Value + "'", con);
    OleDbDataReader oldrread = cmdcheckcodeexit.ExecuteReader();
                    
    while (oldrread.Read())
    {
        dataGridViewpro.Rows[4].Cells["varietycode"].Value = oldrread["varietycode"].ToString();
        MessageBox.Show("Already");
    }
}

让我们仔细看看这一刻,好吗?

Let's have a closer look at this moment, shall we?
OleDbCommand cmdcheckcodeexit = new OleDbCommand("SELECT varietycode FROM product where varietycode='" + dataGridViewpro.Rows[4].Cells["varietycode"].Value + "'", con);

这会生成一个SQL命令:

This generates an SQL command:

SELECT varietycode FROM product where varietycode='???'"

其中代码是您要检查e的值好的 - 它很容易受到SQL注入攻击,但如果你严格控制你的数据网格及其包含的值,这样用户就无法编辑它们,你可以没问题。

然后你查看它返回的每个值并用数据库中的相同值覆盖现有值...为什么?



如果你想知道如果已存在该代码的现有记录,为什么不这样做:

where the code is the value you want to check for existence. OK - it's susceptible to SQL Injection attacks, but provided you tightly control your datagrid and the values it contains so the user can't edit them, you could be ok.
Then you look at each of the values it returns and overwrite the existing value with teh same value from the database...why?

If you want to know if there is already an existing record with that code, why not just do this:

OleDbCommand cmdcheckcodeexit = new OleDbCommand("SELECT Count(varietycode) FROM product where varietycode=@VC, con);
cmdcheckcodeexit.Parameters.AddWithValue("@VC", dataGridViewpro.Rows[4].Cells["varietycode"].Value);
if (cmdcheckcodeexit.ExecuteScaler != 0)
   {
   ...
   }