Reputation: 4596
I'm making a todo list program using windows forms for one of my university assignments. I've learnt how to add and delete items form a list box, so i understand the basic of it but what i want to do is to be able to add a task to a list box like : "get food for dinner," and add that to the listbox but then i want to be able to click on "get food for dinner" and then add another listbox to add stuff like "bread rolls" and "bacon" in the next view which would be linked to the previous item. Like a tree view structure really, but i wanted it more menu orientated. How would i go about to do this, what should i look up?
Side note: feel free to correct my title if it poorly describes what i'm doing, i thought it was better then "using Listbox"
Upvotes: 3
Views: 3868
Reputation: 60466
ToString()
method.If a user clicks on a item you can grab the selected item, cast them to your class and use the properties to do something.
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;
}
}
Add a Todo-List Entry
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);
Do something after a user clicks on a item
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());
}
Upvotes: 4
Reputation: 29668
ListBox items do not have to be Strings they can be any object that can be expressed as a String through ToString.
For example:
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];
Taking this further you can then have:
public class ToDoItem
{
...
public ToDoItem[] Children
{
get;
set;
}
...
}
Very crude but I hope you get what I mean.
Upvotes: 2