I am asked to write a separate class to do something, so I figured I would do this for a to-do list (use a text box to enter data into a list and then have another list for completed tasks, use a button to transfer between).
I have been able to get data added into my to-do list and my code will successfully remove from the to-do list and place in the “Done” list through clicking a button.
My code doesn’t work when I put it in a new class.
Here’s the code of the new class:
public class ToDo : Form1
{
public void Remove()
{
for (int i = 0; i <= (lstToDo.SelectedItems.Count - 1); i++)
{
lstDone.Items.Add(lstToDo.SelectedItems[i]);
lstToDo.Items.Remove(lstToDo.SelectedItems[i]);
}
}
}
and here is the code from Form1 which I think I am attempting to call from when I click on a button:
public void btnRemoveToDo_Click(object sender, EventArgs e)
{
ToDo todo = new ToDo();
todo.Remove();
}
Any help?
Before you moved it into the new class, I imagine your method looked like…
When you moved it into a new class, you changed that code to…
That is creating a new instance of the class. To make it work, you would have to use the existing instance;
thislike so…This isn’t really optimal either though because it is a very awkward architecture. You are better to leave methods which utilize components of the form on the form class itself. If you want methods to process the data, extract the values out of the Form’s components and then use the data as parameters to different classes’ methods. That is more of a comment on general software architechture though and not really important to your specific problem.
EDIT
Casting the Form instance (
this) as aToDoinstance won’t work becauseForm1does not inherit fromToDoas commented on.You are better off moving the
Remove()method back intoForm1class for now. My suggestion would be to try to learn a little bit more about Objects and Object Oriented Programming (OOP) before attempting to break out anything else into different classes.The other thing you could try is making the
Remove()method on theToDoclass take in anything it needs as parameters.Then you would have to make your other method look like this…