动态添加Dropdownlist的SelectedValue不起作用

时间:2016-02-03 20:33:31

标签: c# asp.net

我在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);

我尝试了几个选项来设置所选值无效

我尝试了以下选项来设置所选值                ddCntrl.SelectedValue =&#34; N&#34 ;;               ddCntrl.SelectedIndex = ddCntrl.FindStringExact(&#34; N&#34;)

2 个答案:

答案 0 :(得分:1)

你需要改变一些事情。首先,如果您在构造函数中使用此代码,则需要将其移至LoadShown事件。

在将comboBox添加到面板后设置索引。 ddCntrl.FindStringExact("N")应该可行:

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");

答案 1 :(得分:0)

由于您要绑定到词典,因此您应按如下方式设置所选项目:ddCntrl.SelectedItem = DC[1];

如果您想根据显示值(我真的不建议)进行设置,您必须在DC中找到它,然后将其设置为ddlCntrl