Ant*_*nio 12 c# winforms visual-studio-2013
我从一个创建一个组合框List的KeyValuePair<int, string>.到目前为止,它一直在为用户提供描述性名称,同时返回一个数字ID.
但是,无论我尝试什么,我都无法选择最初选择的值.
public StartUpForm()
{
InitializeComponent();
FlowLayoutPanel flowLayout = new FlowLayoutPanel(); //This is necessary to protect the table, which is for some reason collapsing...
flowLayout.FlowDirection = FlowDirection.TopDown;
flowLayout.AutoSize = true;
flowLayout.AutoSizeMode = AutoSizeMode.GrowAndShrink;
var comboBox = new ComboBox();
{
var choices = new List<KeyValuePair<int, string>> ();
choices.Add(new KeyValuePair<int, string>(1, "hello"));
choices.Add(new KeyValuePair<int, string>(2, "world"));
comboBox.DataSource = choices;
comboBox.ValueMember = "Key";
comboBox.DisplayMember = "Value";
flowLayout.Controls.Add(comboBox);
}
Controls.Add(flowLayout);
//None of these work:
comboBox.SelectedValue = 2;
comboBox.SelectedValue = 2.ToString();
comboBox.SelectedValue = new KeyValuePair<int, string>(2, "world");
comboBox.SelectedValue = "world";
comboBox.SelectedItem = 2;
comboBox.SelectedItem = 2.ToString();
comboBox.SelectedItem = new KeyValuePair<int, string>(2, "world");
comboBox.SelectedItem = "world";
return;
}
Run Code Online (Sandbox Code Playgroud)
结果总是一样的:
如何在ComboBox使用DataSource a中选择最初选择的值List<KeyValuePair<int, string>>?
绑定在构造函数中不能很好地工作,因此尝试将ComboBox声明移动到表单作用域并尝试使用OnLoad覆盖:
ComboBox comboBox = new ComboBox();
protected override void OnLoad(EventArgs e) {
comboBox.SelectedValue = 2;
base.OnLoad(e);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1180 次 |
| 最近记录: |