How to populate textbox with data , using selected

2019-09-02 09:39发布

问题:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    combobox.items.add=("peter magdy");

    if (combobox.selecteditems=("peter magdy")
    textbox.text==("age 23, male, etc");
}

this code helps you to populate textbox with value from combobox

回答1:

Consider this

// your person model where you hold person info
public class Person
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int Age {get; set;}
    public string Sex {get; set;}
}

// You will hold not strings but real objects in combo
private void LoadCombo()
{
    var john = new Pesron(){Id = 0, Name = "John", Age = 20, sex = "Male"};
    var maria = new Pesron(){Id = 1, Name = "Maria", Age = 19, sex = "Female"};
    var couple = new []{john, maria};

    combobox.DataSourse = couple;
    combobox.DisplayMember = "Name";
    combobox.ValueMember = "Id";
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    // Then you can have entire person information at your disposal
    var p = (Person)combobox.SelectedItem;

    textbox.text = string.Format("Name {0}, Age {1}", p.Name, p.Age);
}


回答2:

Try this.

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    comboBox1.Items.Add("peter magdy");

    if (comboBox1.SelectedItem == "peter magdy")
        textBox.Text = "age 23, male, etc";
}

Maybe you will have to change names of components (in code or in the winform designer), though.



回答3:

Textbox have Text property which can set/get text.

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    combobox.items.add=("peter magdy");

    if (combobox.selecteditems=("peter magdy")
        textbox.Text ="age 23, male, etc";
}


回答4:

Try also seeing for SelectionChangeComitted event in place of selectionIndexChange.

SelectionChangeComitted is a last event of the selection which should be the place just before the value is set to comboBox.

SelectedIndex change may not come when when you use up and down arrows in comboBox but the text of comboBox still changes.