C#在更新文本框时从列表框中删除项目

时间:2015-11-25 21:51:41

标签: c# textbox listbox

我正在编写一个C#应用程序,它应该保留字段:名字,姓氏,出生日期和性别。如果我在列表框中选择一个人,它会将列表框中的值映射到相应的文本框中。然后我应该能够:在列表框中添加新记录,修改列表框中的记录,或者删除实际选择的记录。我的问题是,在这两个函数中,应用程序崩溃,索引设置为" -1"。

我的代码:

    class Person
    {
        public string Name{ get; set; }
        public string Surname{ get; set; }
        public DateTime DateOfBirth { get; set; }
        public bool Sex{ get; set; }

        public override string ToString()
        {
            return Name
            + " " + Surname
            + ", nar." + DateOfBirth.ToShortDateString()
            + " (" + (Sex? "male" : "female")
            + ")";
        }
    }

    private void personListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        Persond = (Person) personListBox.Items[personListBox.SelectedIndex];
        NameTextBox.Text = d.Name;
        SurnameTextBox.Text = d.Surname;
        DateOfBirthPicker.Value = d.DateOfBirth;
        FemaleRadioButton.Checked = d.Sex;
    }

    private void modifyRecordButton_Click(object sender, EventArgs e)
    {

            Person d = (Person)personListBox.Items[personListBox.SelectedIndex];
            d.Name= NameTextBox.Text;
            d.Surname= SurnameTextBox.Text;
            d.DateOfBirth= DateOfBirthPicker.Value;
            d.Sex= FemaleRadioButton.Checked;
            detiListBox.Refresh();        
    }

    private void DeleteButton_Click(object sender, EventArgs e)
    {
        personListBox.Items.Remove(detiListBox.SelectedItem);
        personListBox.Refresh();
        Person d = (Person)personListBox.Items[personListBox.SelectedIndex];
        d.Name = NameTextBox.Text;
        d.Surname= PrijmeniTextBox.Text;
        d.DateOfBirth= DateOfBirthPicker.Value;
        d.Sex= FemaleRadioButton.Checked;

    }
}

1 个答案:

答案 0 :(得分:0)

防御性编程要求您在使用之前检查SelectedIndex的值。不要感到惊讶,但是当Listbox没有选择项目时,你得到一个SelectedIndexChanged事件,因此SelectedIndex是-1

private void personListBox_SelectedIndexChanged(object sender, EventArgs e)
{
    if(personListBox.SelectedIndex != -1)
    {
        Persond = (Person) personListBox.Items[personListBox.SelectedIndex];
        NameTextBox.Text = d.Name;
        SurnameTextBox.Text = d.Surname;
        DateOfBirthPicker.Value = d.DateOfBirth;
        FemaleRadioButton.Checked = d.Sex;
    }
}

同样的检查应该应用于modifyRecordButton_Click和deleteRecordButton_Click处理程序