views:

553

answers:

2

When my program loads I read a value from the registry and set a read only combo box to that value however when loaded the combobox shows the item before it in the collection. I'm using the code below to set the text.

RegistryKey OurKey = Registry.CurrentUser;
OurKey = OurKey.OpenSubKey("Software\\test",true);
type = OurKey.GetValue("Type").ToString();
cboType.Text = type;

How should I set the combobox to the value I've read from the registry?

Thanks

A: 

You can add it into the items collection:

int index = cboType.Items.IndexOf(type);
if (index < 0)
{
    cboType.Items.Insert(0, type);
    cboType.SelectedIndex = 0;
}
else
    cboType.SelectedIndex = index;
arbiter
Hi, The value is already in the items collection, how would your code differ?
Setting text property not always select appropriate item from collection. So if 'type' is in collection, and your combobox is read-only it is better to set SelectedIndex instead of Text.
arbiter
+1  A: 

You find the value by it's text value, and then select the returned list item by it's index:

RegistryKey OurKey = Registry.CurrentUser;
OurKey = OurKey.OpenSubKey("Software\\test",true);
type = OurKey.GetValue("Type").ToString();

ListItem selectItem = new ListItem();
selectItem = cboType.Items.FindByText(type);

if (selectItem != null)
{
   cboType.SelectedIndex = cboType.Items.IndexOf(selectItem);
}
chinna