Jonathan Fogelström Jonathan Fogelström - 1 month ago 13
C# Question

ListBox causes program to crash when clicking in an empty area

I'm creating a flip card program that lets you insert a word and it's description. The word is added to a ListBox whilst the description is held in a string array. I've told the program to find the correct description once a ListBox item is clicked as shown in the code below. although this causes the program to crash if the user clicks on an empty area in the ListBox. How can I get around this?

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.
}
}
}


Diagram of my program

Translations:

Infoga: Insert

Redigera: Edit

Note that all the functions in the program are not included in the code!

Answer

ListBox.SelectedIndex is:

A zero-based index of the currently selected item. A value of negative one (-1) is returned if no item is selected

Source

Therefore if no item is selected:

        int b = listBox1.SelectedIndex;
        descriptiontbx.Text = details[b]; 

will cause the crash as b is -1, which is out of range for an array. Add a check to make sure that SelectedIndex >= 0 before trying to use the value.