简体   繁体   English

从数据库插入数据后,如何更改标签的值?

[英]How do I change the value of a label after inserting a data from the Database?

 private void btnCheck_Click(object send, EventArgs ex)
 {      
        string querytxt = @"SELECT Count(itemno) FROM Items WHERE itemno = @itemno";
        SqlConnection cnn = new SqlConnection(@"Data Source=PC80978273\SQLEXPRESS;Initial Catalog=Inventory;User ID=sa;Password=Rmdj1q2w3e!");
        SqlCommand cmd = new SqlCommand(querytxt, cnn);

        cnn.Open();

        cmd.Parameters.AddWithValue("@itemno", txtName.Text);

        int result = (int)cmd.ExecuteScalar();

        if (result > 0)
        {
            btnDelete.Enabled = true;
            SqlConnection conn = new SqlConnection(@"Data Source=PC80978273\SQLEXPRESS;Initial Catalog=Inventory;User ID=sa;Password=Rmdj1q2w3e!");
            SqlCommand cmnd = new SqlCommand("SELECT itemno, categ, name, quant, price FROM Items ", conn);
            conn.Open();
            SqlDataReader dr = cmnd.ExecuteReader();
            if (dr.Read())
            {
                label6.Text = dr.GetValue(0).ToString();
                label1.Text = dr.GetValue(1).ToString();
                label2.Text = dr.GetValue(2).ToString();
                label3.Text = dr.GetValue(3).ToString();
                label4.Text = dr.GetValue(4).ToString();
            }
            txtName.Clear();
            txtName.Enabled = false;
            btnCheck.Enabled = false;
        }
        else
            MessageBox.Show("No data found!");

        cnn.Close();
  }

I have 2 rows of data in the database with "itemno" as my primary key. 我在数据库中有2行数据,其中以“ itemno”作为主键。 The textbox "txtName.Text" is the value of the item number(itemno) in the database. 文本框“ txtName.Text”是数据库中项目编号(itemno)的值。 The value of the labels will depend on the input of txtName.Text. 标签的值将取决于txtName.Text的输入。 However, when i click the "Check" button, it only displays the first row. 但是,当我单击“检查”按钮时,它仅显示第一行。 I have tried enterring the value of "itemno" on the textbox but the labels still display the values of the first row. 我尝试在文本框中输入“ itemno”的值,但标签仍显示第一行的值。 How would I fix this to correct the display of the labels depending on the "itemno" that was entered on the textbox? 我如何解决此问题,以根据在文本框中输入的“ itemno”更正标签的显示?

You should amend your query use where clause to get the desired row on base of value entered in textbox like: 您应该修改查询的使用where子句,以根据在文本框中输入的值来获取所需的行,例如:

int val = Convert.ToInt32(txtName.Text);
string strQuery = "SELECT itemno, categ, name, quant, price FROM Items Where itemno = " + val;
SqlCommand cmnd = new SqlCommand(strQuery, conn);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM