Agnieszka Polec
Agnieszka Polec

Reputation: 1501

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.

Upvotes: 3

Views: 8093

Answers (3)

Sumeshk
Sumeshk

Reputation: 1988

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;

Upvotes: 7

Shell
Shell

Reputation: 6849

try like this,

DataRow[] drs = ((DataTable)cmb.DataSource).Select("Description='" + myText + "'");
if (drs.Length > 0)
{
    cmb.SelectedValue = drs[0]["ID"].ToString();
}
else
{
    //Value not found
}

EDITED:

Sometime when you set the text of combobox will not return the value of ValueMember from SelectedValue it may return null and SelectedIndex may return -1.

Upvotes: 0

Earth
Earth

Reputation: 3571

You can try this

farmRegion.SelectedIndex = farmRegion.FindStringExact(myText)

Another Approach: Note: This may throw argumentexception if the item was not found.

farmRegion.SelectedIndex = farmRegion.Items.IndexOf(myText);

Upvotes: 1

Related Questions