【问题标题】:How do I change the value of a label after inserting a data from the Database?从数据库插入数据后,如何更改标签的值?
【发布时间】:2017-01-05 16:41:30
【问题描述】:
 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”,我将如何解决此问题以更正标签的显示?

【问题讨论】:

  • 使用while (dr.Read()) 代替if (dr.Read())。但是你只会看到最后一个。原因是,您对多条记录只有一个控件。使用DataGridView 或存储当前记录号并实现下一条/上一条记录功能。
  • 您的 fetch 命令未指定哪个 Itemno,因此实际上它会取回所有数据,而且您的代码仅将第一行数据分配给您的标签...
  • 如果您的结果 > 0 比您没有在查询中使用 where 子句 SELECT itemno,categ, name, quant, price FROM Items where itemno = yourtext box value

标签: c# sql-server


【解决方案1】:

您应该修改您的查询,使用 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-09
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2016-01-05
    相关资源
    最近更新 更多