连接ComboBox和TextBox

时间:2016-05-03 21:46:45

标签: c# combobox

我有ComboBox从db获取他的值并且空Textbox没有值。 我希望当我更改ComboBox中的值时,TextBox中的值也会随着db中同一行的值而改变,例如:

--------------------------
| name | price | details |
--------------------------
|bob  f|    12 |   admin |

所以当我选择ComboBox“bob f”时,TextBox会显示“12”。

 private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
 {
     DbCards d = new DbCards();
     DataTable dr = d.GetQuery("SELECT * from Cards").Tables[0];
 }

感谢。

3 个答案:

答案 0 :(得分:2)

你可以通过以下方式做到:

private void Form1_Load(object sender, EventArgs e)
{
    DbCards d = new DbCards();
    DataTable dr = d.GetQuery("SELECT * from Cards").Tables[0];
    comboBox1.DataSource = dr;
    comboBox1.DisplayMember = "name";
    comboBox1.ValueMember = "price";
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    textBox1.Text = comboBox1.SelectedValue.ToString();
}

答案 1 :(得分:1)

您需要做的是,使用name作为其DisplayMemberprice作为其ValueMember的DataTable绑定ComboBox。这样可以在选择更改时采用相应的值。让BindingSoure成为从数据库中填充的数据表;

绑定将是:

BindingSoure= d.GetQuery("SELECT name,price from Cards").Tables[0]
comboBox2.DataSource = BindingSoure;
comboBox2.DisplayMember = "name";
comboBox2.ValueMember = "price";

txtPrice成为您想要显示价格的textBox。所以代码将是:

 txtPrice.Text = comboBox2.SelectedValue.ToString();

答案 2 :(得分:0)

试试这个:

public Form1()
{
    //InitializeComponent();

    var dt = new DataTable();
    dt.Columns.Add("a");
    dt.Columns.Add("b");
    dt.Rows.Add("a1", "b1");
    dt.Rows.Add("a2", "b2");
    dt.Rows.Add("a3", "b3");

    var dgv = new DataGridView { Parent = this, Dock = DockStyle.Top };
    dgv.DataSource = dt;

    var tb = new TextBox { Parent = this, Top = dgv.Bottom };
    tb.DataBindings.Add("Text", dt, "a");

    var cb = new ComboBox { Parent = this, Top = tb.Top, Left = tb.Right + 20 };
    cb.DisplayMember = "a";
    cb.DataSource = dt;
}

充分利用数据绑定功能。