为 ComboBox 选择初始选定的值,其中 KeyValuePair 列表作为数据源 [英] Choosing initially selected value for a ComboBox with a List of KeyValuePair as DataSource

查看:19
本文介绍了为 ComboBox 选择初始选定的值,其中 KeyValuePair 列表作为数据源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 KeyValuePairList 创建一个组合框.到目前为止,它在为用户提供描述性名称的同时向我返回数字 ID 方面效果很好.
但是,无论我尝试什么,我都无法选择最初选择的值.

I am creating a combobox from a List of KeyValuePair<int, string>. So far it has been working very well in offering the user the descriptive name while returning me a numeric id.
However, whatever I try, I am not able to choose the initially selected value.

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> 作为数据源在 ComboBox 中选择初始选定的值?

How can I choose the initially selected value in a ComboBox using as DataSource a List<KeyValuePair<int, string>>?

推荐答案

绑定在构造函数内部不能很好地工作,因此尝试将 ComboBox 声明移动到表单范围并尝试使用 OnLoad 覆盖:

Binding doesn't work very well inside the constructor, so try moving the ComboBox declaration to the form scope and try using the OnLoad override:

ComboBox comboBox = new ComboBox();

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

这篇关于为 ComboBox 选择初始选定的值,其中 KeyValuePair 列表作为数据源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆