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;
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
private void listBox1_Click(object sender, EventArgs e)
if(i == 0) //int i equals the amount of items in the ListBox.
int b = listBox1.SelectedIndex;
descriptiontbx.Text = details[b];
//"details" string array, will open the correct description
//depending on which ListBox item is selected.
A zero-based index of the currently selected item. A value of negative one (-1) is returned if no item is selected
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.