简体   繁体   中英

Set selected value in dynamically created combo boxes

I have created dynamic combo boxes but i am not able to set the value of the combo box

    var list = new List<string>() { "Add","Sub","Mul","Div"};

    for (int i = 0; i < 10; i++)
     {
         var c = new ComboBox();    
         c.DataSource = list.ToList();
         c.selectedvalue="Sub";
         this.flowLayoutPanel1.Controls.Add(c);
      }

You are setting the DataSource of your ComboBox and trying to set the SelectedValue but for this to work correctly you need to set the ValueMember to the name of a member property of your datasource. But, in your case, having a simple list of strings, you cannot use any meaningful property name for SelectedValue.

Change your code to

List<string> list = new List<string>() { "Add","Sub","Mul","Div"};
for (int i = 0; i < 10; i++)
{
    var c = new ComboBox();
    c.Items.AddRange(list.ToArray());
    c.SelectedIndex = 1;
    this.flowLayoutPanel1.Controls.Add(c);
}

Of course you could make this more generic using the IndexOf("Sub") to retrieve the index and replace the fixed 1 that I have used, but in this case it seems useless.

To select a default value of a combobox use the below code.

     c.SelectedIndex = 1;

This will set the start position at the first item in your list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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