I have a ComboBox which is being populated by a LINQ query:
var locations =
from loc in db.LOCATIONs
.Where(a => a.Omit == false)
select new
{
LocationID = loc.LocationID,
Location = loc.Location1
};
cbo = this.cboAdminLocation;
cbo.DataSource = locations;
cbo.DisplayMember = "Location";
cbo.ValueMember = "LocationID";
cbo.SelectedIndex = -1;
I also have a routine DisplayAccounts() which lists all accounts in a DataGridView, but filtered by the value selected in the combo, if selected, or displays all accounts if not. I thought this would be quite simple, and am trying to handle it with the following statements within DisplayAccounts():
if (this.cboAdminLocation.SelectedIndex > -1)
filterAdminLocation = Convert.ToInt32(this.cboAdminLocation.SelectedValue.ToString());
else
filterAdminLocation = 0;
and at the end of the LINQ query:
if (filterAdminLocation > 0)
{
accountData = accountData.Where(a => a.LocationID == filterAdminLocation);
}
However, I am getting an error on the first loop round (i.e. before having a chance to select a value from the Combo) of “Input string was not in the correct format.”, and indeed the value of the combo at this stage is displayed as { LocationID = 1, Location = "Brentwood" } and the selected index is 0. If I skip over this step and test when I have selected a value it returns an integer value as expected.
Therefore, my question is why does get past the if (this.cboAdminLocation.SelectedIndex > -1) test when the selected index is supposedly 0, and more to the point why is the selected index 0 when I explicitly set it to -1 when populating the control?
I appreciate this is probably very simple, but I’m fairly new to C# so you’ll have to excuse my stupidity!
This is because you first populate the comboBox, then set the selected index to
-1. Between this two steps, the selected index is – for a short time –0.In order to correct that, you could call your
DisplayAccounts()routine only after you’ve runcbo.SelectedIndex = -1;. I guess you callDisplayAccounts()in the comboBox’ SelectedIndexChanged event. If so, attach the event to the comboBox after it (and be sure to remove it from the Designer.cs file if you’ve added the event in the Designer window):