简体   繁体   English

comboBox所选值更改

[英]comboBox selected value change

I'd like to give the customer an option to choose a city from COMBOBOX, and once the city's chosen, a list of that city's streets should be in COMBOBOX2. 我想给客户一个选择,从COMBOBOX中选择一个城市,一旦选择了城市,该城市的街道列表应位于COMBOBOX2中。 I tried the following code and I got an error, during the first run, maybe someone can explain this to me? 我尝试了以下代码,但在第一次运行时遇到错误,也许有人可以向我解释一下?

private void Search_by_Apartment_Load(object sender, EventArgs e)
    {
        List<Cities> city = DAL.cities();
        cmBxCity.DataSource = city;//Here he ran the second function, why?
        cmBxCity.DisplayMember = "city";
        cmBxCity.ValueMember = "cityID";
    }

    private void cmBxCity_SelectedIndexChanged(object sender, EventArgs e)
    {

        List<Streets> street = DAL.streets(Convert.ToInt32(cmBxCity.SelectedText));
        // List<Streets> street = DAL.streets(Convert.ToInt32(cmBxCity.SelectedValue));
        comBxStreet.DataSource = street;
        comBxStreet.DisplayMember = "street";
        //cmBxCity.ValueMember = "cityID";

    }

when you assign the DataSource of the cmBxCity control its selectedItem changes from nothing to one item and this triggers the event handler cmBxCity_SelectedIndexChanged . 当您分配cmBxCity控件的DataSource ,其selectedItem将从无更改为一项,这将触发事件处理程序cmBxCity_SelectedIndexChanged

in the question you are talking about COMBOBOX and COMBOBOX2 but in the code there is only one control which is: cmBxCity . 在这个问题中,您正在谈论COMBOBOX和COMBOBOX2,但是在代码中只有一个控件是: cmBxCity

shouldn't you show the streets in the second control called: cmBxStreet ? 您是否不应该在名为cmBxStreet的第二个控件中显示街道?

The SelectedIndexChanged event is fired whenever the selected index is changed programatically or by the user. 每当以编程方式或由用户更改所选索引时,就会触发SelectedIndexChanged事件。

As Davide Pirsa points out, when you change the DataSource of cmBxCity, you are programatically changing the selected index, hence firing the 'cmBxCity.SelectedIndexChanged' event at this line: 正如Davide Pirsa指出的那样,当您更改cmBxCity的数据源时,您将以编程方式更改选定的索引,从而在此行触发'cmBxCity.SelectedIndexChanged'事件:

cmBxCity.DataSource = city;//Here he ran the second function, why? 

One possible solution is to use the SelectionChangeCommitted event instead, which is only fired for changes made by the user. 一种可能的解决方案是改用SelectionChangeCommitted事件,该事件仅针对用户所做的更改而触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM