![](/img/trans.png)
[英]How could I compute the number from the database and show it to the Label everytime I change the combo box value?
[英]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();
}
我在数据库中有2行数据,其中以“ itemno”作为主键。 文本框“ txtName.Text”是数据库中项目编号(itemno)的值。 标签的值将取决于txtName.Text的输入。 但是,当我单击“检查”按钮时,它仅显示第一行。 我尝试在文本框中输入“ itemno”的值,但标签仍显示第一行的值。 我如何解决此问题,以根据在文本框中输入的“ itemno”更正标签的显示?
您应该修改查询的使用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.