【问题标题】:How I Select value from object on the listbox?如何从列表框中的对象中选择值?
【发布时间】:2015-01-10 17:19:46
【问题描述】:
Here is the list item Class:

class ListItem
{
    public string Key;
    public string Value;
    public ListItem()
    {
    }
    public string key
    {
        get { return Key; }
        set { key = value; }
    }
    public string value
    {
        get { return Value; }
        set { Value = value; }
    }
    public override string ToString()
    {
        return Key;
    }
    public string getvalue(string blabla)
    {
        return Value;
    }
}

private void btnOpen_Click(object sender, EventArgs e)
{
    string[] Folders = Directory.GetDirectories(txtFolder.Text);

    foreach (string f in Folders)
    { 
        ListItem n = new ListItem();
        n.Value = f;
        n.Key = Path.GetFileName(f);  
        listBoxSidra.Items.Add(n);
    }
}

private void listBoxSidra_SelectedIndexChanged_1(object sender, EventArgs e)
{
    try
    {
        lblmsg.Text = null;
        comboBoxSeason.Items.Clear();
        string[] seasons = Directory.GetDirectories(listBoxSidra.SelectedValue.ToString());
        for (int i = 0; i < seasons.Length; i++)
        {
            comboBoxSeason.Items.Add(seasons[i]);
        }
        comboBoxSeason.SelectedIndex = 0;
    }
    catch (Exception ex)
    {
        lblmsg.Text = ex.Message;
    }
}

第一种方法:我打开名为 ListItem 的类,它包含文件夹名称(键)和文件夹位置(值)。 第二种方法:我创建了一个数组,其中包含我在文本框上设置的目录中的所有子目录。 我还创建了 ListItem 对象,将其命名为 'n' ,然后将 Values 设置为 'n' ,n.Value(表示目录位置)和 n.Key(表示目录名称)。 下一步是将“n”对象添加到列表框中,现在在列表框中我可以看到目录名称,并且每个对象都包含他的位置。

第三种方法:这就是我卡住的地方,我创建了一个数组,该数组应该包含所选列表框项的子目录,我的意思是,当我单击一个列表框项时,我想获取他的值(值代表位置)并通过将子目录添加到数组中,我应该写什么而不是listBoxSidra.SelectedValue.ToString()

谢谢!

【问题讨论】:

    标签: c# winforms object listbox


    【解决方案1】:

    为了使您的代码正常工作,请进行以下更改

        private void btnOpen_Click(object sender, EventArgs e)
        {
            string[] Folders = Directory.GetDirectories(txtFolder.Text);
    
    
            var dataSource = new List<ListItem>();
            foreach (string f in Folders)
            {
                ListItem n = new ListItem();
                n.Value = f;
                n.Key = Path.GetFileName(f);
                dataSource.Add(n);
            }
    
            listBoxSidra.DataSource = dataSource;
            listBoxSidra.DisplayMember = "key";
            listBoxSidra.ValueMember = "value";
        }
    

    【讨论】:

    • @liavbahar 不要忘记标记对您有帮助的答案 ;-]
    猜你喜欢
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多