YouTube教程无法在列表视图中选择第二个项目(无效参数)

本文关键字:项目 第二个 无效 参数 选择 教程 视图 列表 YouTube | 更新日期: 2023-09-27 18:12:26

我正在尝试跟随并完成这个地址簿教程在YouTube地址簿教程

但是我遇到了一个我不明白的障碍。接下来,我找不到代码中的差异。所以我认为它必须是一个属性设置,我错过了。当我测试填充列表时,我可以选择第一项。但是当我选择第二项时,调试器会弹出一个错误

无效参数= '0'的值对'index'无效

谁能告诉我为什么会抛出这个错误?听视频,代码中的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;
    }  ...
}

YouTube教程无法在列表视图中选择第二个项目(无效参数)

我设法与程序创建者交谈。解决方案是检查和处理无选择。因此,添加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;
}
相关文章: