Reputation: 156
I have the following code:
string checkedItemListBoxPName;
string checkedItemListBoxPID;
int selectedProcessIndex;
private void processes_checkedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == CheckState.Checked)
{
for (int j = 0; j < processes_checkedListBox.Items.Count; ++j)
{
if (e.Index != j)
{
processes_checkedListBox.SetItemChecked(j, false);
}
}
selectedProcessIndex = processes_checkedListBox.SelectedIndex;
MessageBox.Show(selectedProcessIndex.ToString());
string checkedProcess = processes_checkedListBox.Items[selectedProcessIndex].ToString();
string[] checkedProcessElements = checkedProcess.Split(new string[] { ".exe" }, StringSplitOptions.None);
checkedItemListBoxPName = checkedProcessElements[0];
checkedItemListBoxPID = checkedProcessElements[1].Trim();
MessageBox.Show(checkedProcessElements[0].ToString());
MessageBox.Show(checkedItemListBoxPID.ToString());
}
}
This method is called when I check a checkbox from my checkBoxList. In the beginning I am unchecking all the other previous checked boxes so that I will always have just one checked.
In selectedProcessIndex
I store the index of the checked box so that I can access its text a little while after in string checkedProcess = processes_checkedListBox.Items[selectedProcessIndex].ToString();
.
Everything works fine except the fact that when I check the very first box (index = 0) or the 33rd box, I receive System.IndexOutOfRangeException: Index was outside the bounds of the array.
I don't know what is going on with those specific positions. Why 0 and 33 can't be handled. I have 35 checkboxes total, from 0 to 34, as I said. The data from those positions is just like the other, it is visible, and has nothing special. Any suggestion is appreciated!
Upvotes: 1
Views: 78
Reputation: 830
I think you get this error because when you check your elements on position 0 and 33 the method checkedProcess
don't return a string containing the chars ".exe"
. The algorithm tries to split your string. If there isn't found any ".exe"
in it .split()
will return an array with only one element on position zero. In this case the new splitted array is the old unsplitted string).
checkedProcessElements[1].Trim();
tries to read a value outside the arrays range because its length is only 1.
Upvotes: 2