Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# combobox set the value using text

I have a combobox farmRegion that I fill in this way

private void fillRegionData() {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Description", typeof(string));
            farmRegion.ValueMember = "ID";
            farmRegion.DisplayMember = "Description";
            farmRegion.SelectedValue = "ID";
            for (int i = 0; i < StaticData.RegionNames.Count; i++)
            {
                dt.Rows.Add(StaticData.RegionValues[i], StaticData.RegionNames[i]);
            }
            farmRegion.DataSource = dt;
        }

where StaticData.RegionNames is:

public static List<string> RegionNames = new List<string>() { "Select Region", "EASTERN", "WESTERN", "NORTHERN", "EASTERN2", "NORTHERN", "MIDDLE" };

and StaticDate.RegionValues is

public static List<string> RegionValues = new List<string>() { "-10", "1", "2", "3", "4", "5", "6" };

when I save the form, I save the text of the combobox, not the value (this is a requirement issue).

now I want to reload the comboxbox again. I already know the text but I need to make the combobox fires and the option text is already selected.

I tried this:

farmRegion.Text = myText

but still the first option is selected.

like image 728
Agnieszka Polec Avatar asked Apr 28 '26 16:04

Agnieszka Polec


1 Answers

Before setting the text farmRegion.Text = myText put a break point and checks the combobox datasource, and ensure myText is present in combobox.

If you handled any events of combobox put a break point on that events and check what happend after the execution of farmRegion.Text = myText statement.

These two steps doen't solve your issue then find out the index of your text value as

int index = farmRegion.FindString(myText);
farmRegion.SelectedIndex = index;
like image 114
Sumeshk Avatar answered Apr 30 '26 05:04

Sumeshk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!