C# YouTube教程可以';t在Listview中选择第二项(无效参数)

C# YouTube教程可以';t在Listview中选择第二项(无效参数),c#,visual-studio-2010,visual-studio-2008,C#,Visual Studio 2010,Visual Studio 2008,我正试图在YouTube上完成这个地址簿教程 但我遇到了一个我不明白的障碍。接下来,我找不到代码中的差异。所以我想这一定是我缺少的属性设置。当我测试填充列表时,我可以选择第一项。但当我选择第二项时,调试器会抛出一个错误 无效参数=值“0”对“索引”无效 有人能告诉我为什么会抛出这个错误吗?听视频时,代码中的0听起来像是告诉列表一次只能选择一项。不幸的是,我还没有弄明白为什么他的代码有效而我的代码无效 private void button3_Click(object sender, EventA

我正试图在YouTube上完成这个地址簿教程

但我遇到了一个我不明白的障碍。接下来,我找不到代码中的差异。所以我想这一定是我缺少的属性设置。当我测试填充列表时,我可以选择第一项。但当我选择第二项时,调试器会抛出一个错误

无效参数=值“0”对“索引”无效

有人能告诉我为什么会抛出这个错误吗?听视频时,代码中的0听起来像是告诉列表一次只能选择一项。不幸的是,我还没有弄明白为什么他的代码有效而我的代码无效

private void button3_Click(object sender, EventArgs e)
{
    person p = new person(); // creates new string array
    p.Name = textBox1.Text;  // name    
    p.StreetAddress= textBox3.Text; // address
    p.Email = textBox2.Text;  // email
    p.Birthday = dateTimePicker1.Value;  //birthday
    p.AdditionalNotes = textBox4.Text;  // any notes
    people.Add(p); // tells the the above data to be added to the people list.
    listView1.Items.Add(p.Name); // makes its show on the listview of the main box.
    textBox1.Text = "";
    textBox2.Text = "";
    textBox3.Text = "";
    textBox4.Text = "";
    dateTimePicker1.Value = DateTime.Now;

}

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{

    textBox1.Text = people[listView1.SelectedItems[0].Index].Name; //Debugger points error here.
    textBox2.Text = people[listView1.SelectedItems[0].Index].Email;
    textBox3.Text = people[listView1.SelectedItems[0].Index].StreetAddress;
    textBox4.Text = people[listView1.SelectedItems[0].Index].AdditionalNotes;
    dateTimePicker1.Value = people[listView1.SelectedItems[0].Index].Birthday;
}


class person
{
    public string Name
    {
        get;
        set;
    }  ...
}

我设法与程序创建者进行了交谈。解决方案是检查并处理无选择。因此,添加If语句解决了这个问题

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listView1.SelectedItems.Count == 0) return;  // This line added will solve the problem
    textBox1.Text = people[listView1.SelectedItems[0].Index].Name; 
    textBox2.Text = people[listView1.SelectedItems[0].Index].Email;
    textBox3.Text = people[listView1.SelectedItems[0].Index].StreetAddress;
    textBox4.Text = people[listView1.SelectedItems[0].Index].AdditionalNotes;
    dateTimePicker1.Value = people[listView1.SelectedItems[0].Index].Birthday;
}