开发者

Comboboxes only load when selecting the second items and below

This is really strange. I want to select a State and load Cities from that State in another combobox.

It's working EXCEPT when selecting the first item in the combobox:

Here's my entire class. The if statement in the selectedIndexChanged is to make sure that something is selected. The problem is that if I set that to cmbState.SelectedIndex >= 0 then an exception is raised because on initial load the comboBox doesn't has a .State variable there and not a .Value.

I don't know if this makes any sense.

private void MainForm_Load(object sender, EventArgs e)
{
    LoadDepartmentsToComboBox();
}

private void LoadCitiesToComboBox(long StateID)
{
    cmbCity.DataSource = null;
    CityRepository cityRepo = new CityRepository();
    cmbCity.DataSource = cityRepo.FindAllCities().Where(c => c.IDState == StateID);
    cmbCity.DisplayMember = "Name";
    cmbCity.ValueMember = "ID";
}

private void LoadDepartmentsToComboBox()
{
    cmbState.DataSource = null;
    StateRepository stateRepo = new StateRepository();
    cmbState.DataSource = stateRepo.FindAllStates();
    cmbState.DisplayMember = "Name";
    cmbState.ValueMember = "ID";
}

private void cmbState_SelectedIndexChanged(object sender, EventArgs e)
{
    if (cmbState.SelectedIndex > 0)
    {
        LoadCitiesToComboBox(Convert.ToInt64(cmbState.SelectedValue));
    }
}

If I do use cmbState.SelectedIndex >= 0 then I receive this exception:

Unable to cast object of type 'DocumentScannerDanyly.State' to type 'System.IConvertible'.'System.IConvertible'.

When I don't use the SelectedIn开发者_开发知识库dex >= 0 and use plain old >0 then everything works except when selected the first item, which does nothing; understandably because it doesn't take the first item into account.

Thanks a lot for the help.


  1. Don't assign the Display member & the Value member in each load, just assign them once in constructor for example.
  2. add ToList() to the result which will assign to DataSource,

Complex DataBinding accepts as a data source either an IList or an IListSource.

check this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜