ashok kusampudi
ashok kusampudi

Reputation: 13

Dynamically added Dropdownlist's SelectedValue not working

I am creating combobox dynamically in winforms

        ComboBox ddCntrl = new ComboBox();
        ddCntrl.Width = 100;
        ddCntrl.Name="dd_" + tpObj.RowColId;
        ddCntrl.DropDownStyle = ComboBoxStyle.DropDownList;
        Dictionary<int, string> DC = new Dictionary<int, string>();

        DC[-1] = "N/A";
        DC[0] = "Y";
        DC[1] = "N";

        ddCntrl.DataSource = new BindingSource(DC,null);
        ddCntrl.DisplayMember = "Value";
        ddCntrl.ValueMember = "Key";

         ddCntrl.SelectedIndex = ddCntrl.Items.IndexOf("N");
         TableLayoutPanel.Controls.Add(ddCntrl, 1, 1);

I tried couple of option to set the selected value nothing is working

I tried below options to set selected value ddCntrl.SelectedValue ="N"; ddCntrl.SelectedIndex = ddCntrl.FindStringExact("N")

Upvotes: 0

Views: 792

Answers (2)

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

You will need to change some things. First, if you are using this code in the constructor, you will need to move it to Load or Shown event.

And set the index after add the comboBox to the panel. ddCntrl.FindStringExact("N") should works ok:

ComboBox ddCntrl = new ComboBox();
ddCntrl.Width = 100;
ddCntrl.Name = "dd_";
ddCntrl.DropDownStyle = ComboBoxStyle.DropDownList;

Dictionary<int, string> DC = new Dictionary<int, string>();
DC[-1] = "N/A";
DC[0] = "Y";
DC[1] = "N";

ddCntrl.DataSource = new BindingSource(DC, null);
ddCntrl.DisplayMember = "Value";
ddCntrl.ValueMember = "Key";

tableLayoutPanel.Controls.Add(ddCntrl, 1, 1);
ddCntrl.SelectedIndex = ddCntrl.FindStringExact("N");

Upvotes: 1

Onur Omer
Onur Omer

Reputation: 526

Since you are binding to a Dictionary you should set selected item as follows:ddCntrl.SelectedItem = DC[1];

If you would like to set depending on display value (which i really do not suggest) you have to find it in DC and then set it to ddlCntrl

Upvotes: 0

Related Questions