我正在尝试跟进并完成YouTube Address Book Tutorial
上的地址簿教程但是我遇到了一些我不明白的障碍。接下来我找不到代码的区别。所以我认为它必须是我失踪的财产设置。当我测试填充列表时,我可以选择第一个项目。但是当我选择第二项时,调试器会发出错误
无效参数=' 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;
} ...
}
答案 0 :(得分:1)
我设法与程序创建者交谈。解决方案是检查并处理没有选择。因此,添加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;
}