Skip to main content
 首页 » 编程设计

c#之为什么我的表单在关闭时仍然向列表中添加一个项目

2024年02月06日17TianFang

到目前为止,我有一个 form1,我在其中按下一个按钮,它将加载第二个表单,其中有几个文本框和一个组合框供用户填写,然后将其添加到显示的列表中form1 上的 ListView 。但是,它工作正常,除非我使用按钮或按角落的红色 X 关闭第二个表单,它仍然会向列表中添加一个空白项。这并不是我真正想要的。

这是我为 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"); 
        } 
    } 

然后我的第二个表单上的用户输入数据的代码是这样的。

  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; 
      } 
  } 

我只是不明白,当我按红色 X 关闭第二个表单时,它会向列表/ ListView 添加一个空白项?

请您参考如下方法:

您没有检查 ShowDialog() 的 DialogResult:

newTaskForm frm2 = new newTaskForm(); 
if (frm2.ShowDialog() != DialogResult.OK) 
   return; 
NewTask task = new NewTask(); 

或

newTaskForm frm2 = new newTaskForm(); 
DialogResult res = frm2.ShowDialog(); 
if (res != DialogResult.OK) 
   return; 
NewTask task = new NewTask(); 

我建议对 newTaskForm 进行改进:

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) 
  { 
      MessageBox.Show("Please fill in all fields"); 
  } 
  else 
  { 
      DialogResult = DialogResult.OK; 
      Close(); 
  } 
}