使用ListBox存储多个数据

时间:2012-02-13 14:24:19

标签: c# winforms listbox

我正在使用Windows表单为我的大学作业制作一个待办事项列表程序。我已经学会了如何从列表框中添加和删除项目,所以我理解它的基本但我想要做的是能够将任务添加到列表框中,如:“获取晚餐的食物”,以及将其添加到列表框但我希望能够点击“获取晚餐的食物”,然后添加另一个列表框,在下一个视图中添加“面包卷”和“培根”等内容,这些内容将链接到上一个项目。 就像树视图结构一样,但我希望它更加面向菜单。 我该怎么做呢,我该怎么看?

附注:如果它描述的是我正在做什么,我可以随意纠正我的标题,我认为它比“使用Listbox”更好

2 个答案:

答案 0 :(得分:4)

描述

  1. 为您的Todo列表条目创建基类。
  2. 覆盖ToString()方法。
  3. 使用您的班级列表填充您的列表框。
  4. 如果用户点击某个项目,您可以获取所选项目,将其投放到您的班级并使用这些属性执行某些操作。

    示例

    public class MyTodoListEntry
    {
        public string Title { get; set; }
        public DateTime DueDate { get; set; }
        public List<string> Information { get; set; }
    
        public MyTodoListEntry()
        {
            this.Information = new List<string>();
        }
    
        public override string ToString()
        {
            return this.Title;
        }
    }
    

    添加Todo-List条目

    MyTodoListEntry entry = new MyTodoListEntry();
    entry.Title = "get food for dinner";
    entry.Information.Add("bread rolls");
    entry.Information.Add("bacond");
    entry.DueDate = new DateTime(2012,12,12);
    myListBox.Items.Add(entry);
    

    用户点击商品后执行某项操作

    private void myListBox_Click(object sender, EventArgs e)
    {
        if (myListBox.SelectedItem == null)
            return;
    
        // get selected TodoList Entrie
        MyTodoListEntry selectedEntry = (MyTodoListEntry)myListBox.SelectedItem;
        // do something, for example populate another ListBox with selectedEntry
        myInformationsListBox.Items.Clear();
        myInformationsListBox.Items.AddRange(selectedEntry.Information.ToArray());
    }
    

    截图

    enter image description here

答案 1 :(得分:2)

ListBox项不必是字符串,它们可以是任何可以通过ToString表示为String的对象。

例如:

public class ToDoItem
{

   public ToDoItem(string w)
   {
       What = s;
   }

   public override string ToString()
   {
       return What;
   }

   public string What
   {
        get;
        set;
   }

}

myListBox.Items.Add(new ToDoItem("Feed Budgie"));

ToDoItem item = (ToDoItem)myListBox.Items[0];

更进一步,您可以:

public class ToDoItem
{
    ...
    public ToDoItem[] Children
    {
       get;
       set;
    }
    ...
}

非常粗暴,但我希望你明白我的意思。