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

C# C在更新文本框时从列表框中删除项,c#,textbox,listbox,C#,Textbox,Listbox,我正在写一个C应用程序,它应该保存字段:名字、姓氏、出生日期和性别。如果我在列表框中选择一个人,它会将列表框中的值压缩到相应的文本框中。然后,我应该能够:将新记录添加到列表框中,修改列表框中的记录,或者删除实际选择的记录。我的问题是,在这两个函数中,应用程序在索引设置为-1时崩溃 我的代码: class Person { public string Name{ get; set; } public string Surname{ get; set;

我正在写一个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;

    }
}

防御性编程要求在使用SelectedIndex之前检查其值。不要惊讶,但是当列表框没有选择项时,您会得到一个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\u Click和deleteRecordButton\u Click处理程序也应进行相同的检查

在列表中执行操作时,应始终确保索引大于-1。同时查看删除处理程序中的代码。最好先读取ListIndex并从db中执行remove,然后再从Listbox中删除该项。OK,将这样做。最后一件事——我注意到modifyRecordButton_Click实际上没有修改任何内容。你知道为什么吗?你如何将个人数据绑定到你的列表框?换句话说。如果要将Listbox的DataSource属性设置为某种集合,则应使用BindingSource组件进行设置,该组件提供基础结构,以便在更改当前选定项的属性后刷新该项。这不是自动发生的