gpt4 book ai didi

c# - 为具有 KeyValuePair 列表的 ComboBox 选择最初选择的值作为 DataSource

转载 作者:可可西里 更新时间:2023-11-01 08:25:49 26 4
gpt4 key购买 nike

我正在从 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;
}

结果总是一样的:

enter image description here

如何在 ComboBox 中选择最初选择的值使用 List<KeyValuePair<int, string>> 作为数据源?

最佳答案

绑定(bind)在构造函数中不能很好地工作,所以尝试将 ComboBox 声明移动到表单范围并尝试使用 OnLoad 覆盖:

ComboBox comboBox = new ComboBox();

protected override void OnLoad(EventArgs e) {
comboBox.SelectedValue = 2;
base.OnLoad(e);
}

关于c# - 为具有 KeyValuePair 列表的 ComboBox 选择最初选择的值作为 DataSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32750162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com