Fejs
Fejs

Reputation: 2888

C# Winforms: Set text in ComboBox based on selected Item

I'm new to c# and I'm now learning how to trigger events based on some form actions.

This is part of view:

private void comboGoodsName_TextChanged(object sender, EventArgs e)
{
    controller.selectName(comboGoodsName.Text);
}

public void nameChanged(object sender, MeasurementEventArgs e)
{
    comboGoodsName.TextChanged -= comboGoodsName_TextChanged;
    comboGoodsName.Text = e.value;
    comboGoodsName.TextChanged += comboGoodsName_TextChanged;
}

And this is part of controller:

public void selectName(string name)
{          
    model.Name = name.Split('|')[0].Trim();

    if (name.Contains(" | "))
    {
        string code = name.Split('|')[1].Trim();
        model.NameCode = code;
    }
}

The scenario is as follows:
I want to have a ComboBox with some items in it (doesn't matter what's the source). Items are combination of name and code in following format: NAME | CODE. When I enter some text in ComboBox (type it in), comboGoodsName_TextChanged is triggered, which in turn calls selectName which sets model's property, which in turn raises an event which is observed by nameChanged. This works fine, as expected (puts NAME in ComboBox and CODE to TextBox - not shown as not relevant). Problem shows up when I select item from ComboBox drop-down list. When I select item, instead of showing NAME in ComboBox, I see NAME | CODE.

Edit: In the model, property is set correctly, which I confirmed by printing its value. So, issue is related only to displaying proper value in ComboBox.

Upvotes: 2

Views: 1434

Answers (1)

Stinky Towel
Stinky Towel

Reputation: 778

Try this:

private void comboGoodsName_SelectedIndexChanged(object sender, EventArgs e)
{
    // if combobox has selected item then continue
    if (comboGoodsName.SelectedIndex > -1)
    {
        // split the selecteditem text on the pipe into a string array then pull the first element in the array i.e. NAME
        string nameOnly = comboGoodsName.GetItemText(this.comboGoodsName.SelectedItem).Split('|')[0];

        // handing off the reset of the combobox selected value to a delegate method - using methodinvoker on the forms main thread is an efficient to do this
        // see https://msdn.microsoft.com/en-us/library/system.windows.forms.methodinvoker(v=vs.110).aspx
        this.BeginInvoke((MethodInvoker)delegate { this.comboGoodsName.Text = nameOnly; });
    }      
}

Upvotes: 1

Related Questions