So far, I have a form1 where I press a button, it will load up a second form which has a couple of textboxes and a combobox to be filled in by the user which will then be added a to a list displayed in a listview on the form1. However, it works fine except when i close the second form either using a button or pressing the red X in the corner, it still adds a blank item to the list. Which is not really what I want it to do.
This is my code for the button on form1:
private void button1_Click(object sender, EventArgs e)
{
// if there is less than items in the list, load the form
if (addTask.Count < 10)
{
// New instance to load the form
newTaskForm frm2 = new newTaskForm();
frm2.ShowDialog();
NewTask task = new NewTask();
// Get the values entered by the user, eg title will be the text in textBox1 etc.
task.title = frm2.textBox1.Text;
task.description = frm2.textBox2.Text;
try
{
task.priority = frm2.comboBox1.SelectedItem.ToString();
}
catch
{
}
task.completionDate = frm2.dateTimePicker1.Value.ToString();
addTask.Add(task); // Add task to the list
listView1.Items.Add(task.title); // Display task title in the list view
// close form
frm2.Close();
frm2.Dispose();
}
// if there are 10 items in the list, display a message
else
{
MessageBox.Show("Maximum number of tasks added");
}
}
Then the code on my second form where the user enters the data is this.
private void button1_Click(object sender, EventArgs e)
{
// check to see if all the fields have been filled in properly
if (string.IsNullOrWhiteSpace(textBox1.Text) || string.IsNullOrWhiteSpace(textBox2.Text) || comboBox1.SelectedItem == null)
{
DialogResult = DialogResult.None; // do not send results back to main form
MessageBox.Show("Please fill in all fields");
}
else
{
DialogResult = DialogResult.OK;
}
}
I just don't understand that when I press the Red X to close the second form, it adds a blank item to the list/listview?
Aucun commentaire:
Enregistrer un commentaire