[英]Choosing initially selected value for a ComboBox with a List of KeyValuePair as DataSource
我正在从KeyValuePair<int, string>
的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;
}
结果总是一样的:
如何使用List<KeyValuePair<int, string>>
作为DataSource在ComboBox
选择最初选择的值?
绑定在构造函数中不能很好地工作,因此尝试将ComboBox声明移动到表单作用域并尝试使用OnLoad覆盖:
ComboBox comboBox = new ComboBox();
protected override void OnLoad(EventArgs e) {
comboBox.SelectedValue = 2;
base.OnLoad(e);
}
你为什么要使用绑定? 使用int和string属性创建一个类并覆盖ToString()以显示字符串文本会不会更容易:
public class ComboItem
{
public int Key {get; set;}
public string Text {get; set;}
public override string ToString()
{
return this.Text;
}
}
public void OnFormLoad(object Sender, ...)
{
IEnumerable<ComboItem> comboItems = CreateListComboItems();
this.ComboBox1.Items.Clear();
foreach (var comboitem in comboItems)
{
this.comboBox1.Items.Add(comboItem);
}
}
订阅comboBox事件SelectedIndexChanged:
private void OnComboSelectedIndexChanged(object sender, EventArgs e)
{
ComboItem selectedItem = (ComboItem)this.comboBox1.SelectedItem;
ProcessSelectedKey(selectedItem.Key);
}
附录:我无法选择最初选择的值。
我想你希望能够以编程方式选择具有给定值的Key的组合框项,从而使ComboBox显示属于该键的Text。
尽管属性ComboBox.Items的类型为ComboBoxCollection,但它实现了IEnumerable,这意味着您可以在其上使用Enumerable.Cast()将其强制转换为ComboItems序列。 使用Linq查找是否存在具有所请求密钥的ComboItem并选择第一个找到的ComboItem,或者如果没有具有此密钥的ComboItem则选择或选择任何内容
// selects the combobox item with key == value
private void SelectComboItem(int value)
{
this.comboBox1.SelectedItem =
this.ComboBox1.Items.Cast<ComboItem>()
.FirstOrDefault(comboItem => comboItem.Key == value);
}
代码将获得组合框中的项集合(我们知道它是一系列ComboItems),因此我们可以将所有项目转换为ComboItem。 然后我们尝试找到第一个Key等于value的ComboItem。 如果没有这样的ComboItem,则返回null。 最后使它成为选定的项目。 值null表示不选择任何内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.