Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

c# - ComboBox has its old value after Clear()

I have two comboBox cb_Brand and cb_Model on a winForm.

cb_Model populates values on brand Select. the problem is: if we select the brand any and select the any model under that brand, cb_Model does not loose the value of previous model selected. for example: If we select the brand Audi and model A3 and the select the Brand Ford, when I click on cb_Model to select the model, it displayed the A3 as selected model, but still other models in list are belong to ford.

my code is:

private void cb_Brand_SelectedIndexChanged(object sender, EventArgs e)
{
    // Clear Current Data
    cb_Model.Text = "";
    cb_Model.Items.Clear();

    CarModel _carmodel = new CarModel ();

    // Get Selected Car Brnad
    int CarBrandID = _carmodel .GetCarBrandID(cb_Brand.Text);

    //Enable choice of Model
    SortedList<int, Model> colM;

    colM = Model.ReadModel(CarBrandID);

    cb_Model.DisplayMember = "ModelText";
    foreach (Model objM in colM.Values)
    {
        cb_Model.Items.Add(objM);
    }
}

Any Idea Please.. Thanks


unable to find the reason but sorted out with a temp fix:

private void cb_Model_Click(object sender, EventArgs e)
{
    cb_Model.Text = "";
}

Thanks a lot guys cheers

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of adding the items manually like this:

foreach (Model objM in colM.Values)
{
    cb_Model.Items.Add(objM);
}

Let .NET take care of it for you and replace it with this:

cb_Model.DataSource = colMValues;

Which will bind the data to the list and refreshes the comboboxes items automatcially when a data source is set.

You will also not need these lines anymore:

// Clear Current Data
cb_Model.Text = "";
cb_Model.Items.Clear();

Have a read of this for more info on binding lists (and other data sources) to ComboBoxes:

How to: Bind a Windows Forms ComboBox or ListBox Control to Data (MSDN)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...