如何阻止重复值? [英] How to stop duplicate value?

查看:93
本文介绍了如何阻止重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,



当我点击保存按钮并告诉我它已经存在时,如何删除重复的名称



i使用上面的代码从数据库中保存名称,地址等。



Dear All,

How could be remove the duplicate name when I click on save button and tell me it’s already exists

i am using above code for save name ,address etc. from the database.

private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string connstr = @"Server=.\SQLEXPRESS ;Initial Catalog=RPSJDB;Integrated Security=True; Max Pool Size=100";
                string query = "insert into CustomerTable values('" + txtCustomerName.Text + "','" + txtAddress.Text + "','" + txtMobileNo.Text + "','" + lblGoldBalance.Text + "','" + lblSilverBalance.Text + "','" + lblCashBalance.Text + "')";
                SqlConnection conn = new SqlConnection(connstr);

                if (txtCustomerName.Text != "" & txtAddress.Text != "")
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand(query, conn);
                    cmd.ExecuteNonQuery();

                    txtCustomerName.Clear();
                    txtAddress.Clear();
                    txtMobileNo.Clear();

                    MessageBox.Show("Values Save in DataBase");
                    conn.Close();
                }
                else
                {
                    MessageBox.Show("Only Mobile Field Can be Empty");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("At Least 0 value can be save in the Gold Silver Cash Area",ex.Message);
                
            }

推荐答案

您好,

您可以创建一个检查功能数据库中的值

这里是示例代码。

1:您将编写一个函数

Hi,
You can create a function which checks for the value from data base
here is the sample code.
1:You will write a function
private Boolean usernameexists()
      {

              OleDbCommand com = new OleDbCommand("select Username from User_master where        Username ='" + txt_username.Text + "'", con);
              OleDbDataReader oledbrd1;
              oledbrd1 = com.ExecuteReader();
              if (oledbrd1.HasRows)
              {
                  oledbrd1.Read();
                      unameerrmsg.Visible = true;
                      unameerrmsg.Text = "username already exist";
                      oledbrd1.Close();
                      return true;

              }
              else
              {
                  unameerrmsg.Visible = false;
                  return false;
              }
          }





2:如果存在用户名,则在保存按钮上返回



2: On your save button if username exist return

if (usernameexists() == true)
           {
               return;
           }





您也可以在textbox上调用此函数textchanged()



希望这有帮助

快乐编码:)



You can also call this function on textbox textchanged()

hope this helps
Happy coding :)


这篇关于如何阻止重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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