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();
}
我在数据库中有两行数据" itemno"作为我的主键。文本框" txtName.Text"是数据库中项目编号(itemno)的值。标签的值将取决于txtName.Text的输入。但是,当我点击"检查"按钮,它只显示第一行。我试过输入" itemno"的值。在文本框上,但标签仍显示第一行的值。我如何解决此问题以根据" itemno"更正标签的显示?那是在文本框中输入的?
答案 0 :(得分:0)
您应修改查询使用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);