简体   繁体   中英

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. The textbox "txtName.Text" is the value of the item number(itemno) in the database. The value of the labels will depend on the input of 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. How would I fix this to correct the display of the labels depending on the "itemno" that was entered on the textbox?

You should amend your query use where clause to get the desired row on base of value entered in textbox like:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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