Pages

Showing posts with label Visual Studio 2010 Tutorial. Show all posts
Showing posts with label Visual Studio 2010 Tutorial. Show all posts

Tuesday, March 5, 2013

Propertybinding Combobox Values

 Ok, you have a search dialog box and you'd like to store the user's last choice for use the next time he launches your program.

So you go into "PropertyBinding" and there is no way to bind this value.


SelectedIndex and SelectedText are not in the list.  Text will not work if your box is a DropDownList, it will only work if your Combobox is a Dropdown.
So here's what you have to do.

First, from your project, Select Project and <projectname> Properties.
Then add a user scoped string setting for your Combobox.
Don't save the SelectedIndex as an integer, because whenever the list changes, you'll be restoring the wrong item in the list.

private void FindDropDownValue(ComboBox ddl, string value, int defaultvalue)
{
    int selectedListItem = ddl.Items.IndexOf(value);
    if (selectedListItem == -1)
    {
        selectedListItem = defaultvalue;
    }
    ddl.SelectedIndex = selectedListItem;
}

private void Load_Dropdowns()
{
//reload user settings
    FindDropDownValue(cbCustomer, Properties.Settings.Default.Quote_Customer, 0);
}
This will load the values from the user settings store.   I suggest calling Load_Dropdowns from your FORM_LOAD() method.

Now all we need is to save the settings on Form_Closing() of the form.

Private void SaveUserSettings()
{
    Properties.Settings.Default.Quote_Customer = cbCustomer.Text;
}

private void QuoteForm_FormClosing(object sender, FormClosingEventArgs e)
{
    SaveUserSettings();
}




Bryan Valencia is a contributing editor and founder of Visual Studio Journey.  He owns and operates Software Services, a web design and hosting company in Manteca, California.

Tuesday, February 12, 2013

DropdownList: SelectedValue does nothing.

 I have a ComboBox set as a DropDownList, and the SelectedValue property, which ostensibly will find and select the selected value, does not.

cbSalesman.SelectedValue = salesman;  This is probably because you would need to give it not just a string to look for, but an actual object that is a member of the Items list.  That would require ugly gyrations along the lines of the following.
  1. get the string to look for
  2. get the index of that string in the dropdown (using Items.IndexOf)
  3. grab the item at that index
  4. feed it to the "SelectedValue" property.
Instead of all that, why not just do this.

cbSalesman.SelectedIndex = cbSalesman.Items.IndexOf(salesman);


...

Bryan Valencia is a contributing editor and founder of Visual Studio Journey.  He owns and operates Software Services, a web design and hosting company in Manteca, California.

Share This!

Contact Us

Name

Email *

Message *