繁体   English   中英

我将如何获得SelectedItem? C#Winforms CheckedListBox控件

[英]How will I get the SelectedItem? C# winforms CheckedListBox control

在提出这个问题之前,我曾在这个网站上问过这个问题。 (乔恩·斯基特先生回答了!)

我在检索CheckedListBoxSelectedItem时遇到困难。 请考虑我的代码:

public class StaticValues
{
    private string value;
    private string display;
    public StaticValues(string val, string disp)
    {
        this.value = val;
        this.display = disp;
    }

    public string Value
    {
        get
        { return value; }
    }

    public string Display
    {
        get
        { return display; }
    }
}

private void Form3_Load(object sender, EventArgs e)
{
    ArrayList dataSource = new ArrayList();
    dataSource.Add(new StaticValues("001", "Item 1"));
    dataSource.Add(new StaticValues("002", "Item 2"));
    dataSource.Add(new StaticValues("003", "Item 3"));
    checkedListBox1.DataSource = dataSource;
    checkedListBox1.DisplayMember = "Display";
    checkedListBox1.ValueMember = "Value";
}

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(checkedListBox1.SelectedValue.ToString()); // outputs correct SelectedValue 
    MessageBox.Show(checkedListBox1.SelectedItem.ToString()); // this one doesn't for SelectedItem
}

我将如何获得SelectedItem

鉴于它是复选框列表,我怀疑最好使用CheckedListBox.CheckedIndices属性查找所有选中的项目。 从那里,您可以转到单个项目并从中找到适当的值。 DisplayMember工作时,我怀疑您最好将项目转换为已知类型并以这种方式找到值,除非这对您来说真的很尴尬。 可能还有另一种解决方法,但我不知道。 请注意, CheckedListBox.ValueMember的文档声称它“与此类无关”。

最初没有选定的项目,至少直到用户选择一个为止。 要检索用户选择的值,您必须对wselectedIndexChanged事件做出反应,并且如果用户将该值更改为OnSelectedValueChanged事件。

如果要查找设置了复选框的项目,则需要查看CheckecItemCollection和CheckedIndexCollection属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM