簡體   English   中英

C#在更新文本框時從列表框中刪除項目

[英]C# removing item from listbox while updating textboxes

我正在編寫一個 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 之前檢查它的值。 不要感到驚訝,但是當 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 處理程序應用相同的檢查

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM