Skip to main content
 首页 » 编程设计

c#之如何从 SQL 数据库添加组合框项目

2024年02月13日15Leo_wl

我需要从 SQL db 将项目添加到组合框。在我的表单中有 1 个组合框(用于项目)和 1 个 文本框(用于值)。我需要从数据库表中将项目加载到两者,并且应根据组合框的值选择 textbox 的值。

例如:

combobox           textbox   
-------------------------- 
 Items          price   
 sss             100        
 ddd             140   
 fff             220 

选择组合框值时应自动选择文本框值。

private void Form4_Load(object sender, EventArgs e) 
        { 
            con = new SqlConnection("data source=PC\\SQLEXPRESS;integrated security=true;Initial catalog=MyDB"); 
            BindData1(); 
} 
 public void BindData1() 
        { 
 
 
            con.Open(); 
            string strCmd = "select Items from tblbill"; 
            SqlCommand cmd = new SqlCommand(strCmd, con); 
            SqlDataAdapter da = new SqlDataAdapter(strCmd, con); 
            DataSet ds = new DataSet(); 
            da.Fill(ds); 
            cmd.ExecuteNonQuery(); 
            con.Close(); 
 
            comboBox1.DisplayMember = "items"; 
            comboBox1.ValueMember = "items"; 
            comboBox1.DataSource = ds.Tables[0]; 
 
            comboBox1.Enabled = true; 
 
        } 
 
 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
        { 
 
            con.Open(); 
           string sel = comboBox1.SelectedItem.ToString(); 
 
 
 
           SqlCommand cmd = new SqlCommand("select price from tblbill where items=" + comboBox1.SelectedValue, con); 
 
            SqlDataReader dr = cmd.ExecuteReader(); 
            while (dr.Read()) 
            { 
                p = dr[0] as string; 
                //department = reader[1] as string; 
 
            } 
 
            textBox1.Text = p; 
            con.Close(); 
        } 

我的组合框中充满了 tblbill 中的项目,但无法根据 combobox 中的选择在 textbox 中显示价格值。

请帮帮我

请您参考如下方法:

这样试试

SqlCommand cmd = new SqlCommand("select price from tblbill where items=@price", conn); 
command.Parameters.AddWithValue("@price", comboBox1.SelectedValue.ToString()); 
//no need to use reader use  
var value= (int)cmd.ExecuteScalar();//set data type according to your use 
textBox1.Text = value.ToString(); 

使用 sqlparameter 来避免 sql 注入(inject),并使用 execute scalar,因为你试图只为所选产品获取一个价格