C# 在空白区域单击时,ListBox会导致程序崩溃
我正在创建一个翻转卡片程序,可以让你插入一个单词及其描述。单词被添加到列表框中,而描述被保存在字符串数组中。我已经告诉程序在单击列表框项目后查找正确的描述,如下面的代码所示。但如果用户单击列表框中的空白区域,则会导致程序崩溃。我怎样才能避开这件事C# 在空白区域单击时,ListBox会导致程序崩溃,c#,visual-studio-2015,listbox,C#,Visual Studio 2015,Listbox,我正在创建一个翻转卡片程序,可以让你插入一个单词及其描述。单词被添加到列表框中,而描述被保存在字符串数组中。我已经告诉程序在单击列表框项目后查找正确的描述,如下面的代码所示。但如果用户单击列表框中的空白区域,则会导致程序崩溃。我怎样才能避开这件事 public partial class Form1 : Form { int i = 0; string[] details = new string[20]; private void insertbtn_Click(ob
public partial class Form1 : Form
{
int i = 0;
string[] details = new string[20];
private void insertbtn_Click(object sender, EventArgs e)
{
listBox1.Items.Add(inserttbx.Text); //Adds word to the ListBox
}
private void editDescbtn_Click(object sender, EventArgs e)
{
details[i] = descriptiontbx.Text; //adds text from descriptiontbx to "details" array
i++;
}
private void listBox1_Click(object sender, EventArgs e)
{
if(i == 0) //int i equals the amount of items in the ListBox.
{
}
else
{
int b = listBox1.SelectedIndex;
descriptiontbx.Text = details[b];
//"details" string array, will open the correct description
//depending on which ListBox item is selected.
}
}
}
翻译:
Infoga:插入雷迪格拉:编辑
请注意,代码中不包括程序中的所有函数
列表框。选择的索引是:
当前选定项的从零开始的索引。如果未选择任何项目,则返回负值(-1)
因此,如果未选择任何项目:
int b = listBox1.SelectedIndex;
descriptiontbx.Text = details[b];
将导致崩溃,因为b为-1,这超出了数组的范围。在尝试使用该值之前,添加一项检查以确保SelectedIndex>=0