We have a project that sets the DataSource of a combobox, but allows users to either select something from this list OR type in an item not contained in the list. Basically, there is a Geobase that contains streets, but the users are not required to choose a street from the list. The ComboBox.DropDownStyle is set to DropDown.
If a user edits a record that contains a street NOT in the geobase (and therefore not in the ComboBox.DataSource) we are having issues populating the form correctly.
Here is a greatly simplified form of our problem:
private void button1_Click(object sender, EventArgs e)
{
// Create a new form. In the constructor the DataSource of the ComboBox is set with three items:
// Main St., First St., and Second St.
ComboBoxTrialForm frm = new ComboBoxTrialForm();
// Set comboBox1.Text equal to an item NOT in the datasource
frm.SetComboTextValue("Michigan Ave.");
// Show the form, and the comboBox has the first item in its datasource selected
frm.Show();
}
The ComboBoxTrial Class goes something like this:
public partial class ComboBoxTrialForm : Form
{
public ComboBoxTrialForm()
{
InitializeComponent();
List<string> streets = new List<string>() { "Main St.", "First St.", "Second St." };
comboBox1.DataSource = streets;
}
public void SetComboTextValue(string text)
{
comboBox1.Text = text;
}
}
I set break points and found that comboBox1.Text does indeed get set correctly. Interestingly I found that the BindingContextChanged event actually gets fired twice in this simplified example. Once in the constructor when comboBox1.DataSource = streets is called, and a second time when frm.Show() is called.
Why is this event firing when the form is shown, and is this why my manually set selection is getting removed? How should I go about correcting this behavior?
Also, am I incorrect in thinking that I should be able to use the combobox in this way?
Thanks in advance.
You should be able to set the SelectedIndex to -1 so that no item is selected in the list. I didn’t have any problem getting “Michigan Ave.” to display in the combo box with this method.
Also, you could show the form, and then set the text. Unless that’s a problem, the user probably won’t notice.