M. rit
M. rit

Reputation: 61

Connect between ComboBox and TextBox

I have ComboBox that gets his values from db and empty Textbox that gets no value. I want that when i change the value in the ComboBox the value in the TextBox will change also with the value of the same row in the db for example:

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

so when i choose in the ComboBox "bob f" the TextBox will show "12".

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

thanks.

Upvotes: 2

Views: 153

Answers (3)

Alexander Petrov
Alexander Petrov

Reputation: 14251

Try this:

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;
}

Use full power of data bindings.

Upvotes: 0

Abdellah OUMGHAR
Abdellah OUMGHAR

Reputation: 3745

You can do that by :

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();
}

Upvotes: 2

sujith karivelil
sujith karivelil

Reputation: 29036

What you need to do is, Bind the ComboBox using a DataTable with name as its DisplayMember and price as its ValueMember. So that The corresponding value can be taken up on selection changes. Let BindingSoure be a datatable which is populated from the database;

Binding will be:

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

Let txtPrice be the textBox in which you wanted to show the Price as well. so the code for that will be:

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

Upvotes: 1

Related Questions