使用datagridview避免数据库中的重复值以避免它。 [英] Avoid the duplicate value from database using datagridview to avoid it..

查看:104
本文介绍了使用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)
   {
   ...
   }


这篇关于使用datagridview避免数据库中的重复值以避免它。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆