我正在尝试制作一个checkBoxList,每当我检查/取消选中一个项目时它会向下/向上排序,这样未经检查的项目将位于顶部,并且检查将位于底部。为此我创建了一个事件checkedListBox1_SelectedIndexChanged。我的问题是如何检查选择它,我得到一个例外。我假设这是因为它正在改变,而我正在检查当前状态是什么
这是我的代码:
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var items = checkedListBox1.Items;
List<string> checkedList = new List<string>();
List<string> uncheckedList = new List<string>();
int selected = checkedListBox1.SelectedIndex;
string state = checkedListBox1.GetItemCheckState(checkedListBox1.Items.IndexOf(selected)).ToString();
//error: An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll
//Additional information: InvalidArgument = Value of '-1' is not valid for 'index'.
if (state == "Checked")
uncheckedList.Add(selected.ToString());
else
checkedList.Add(selected.ToString());
foreach (var item in items)
{
int index = checkedListBox1.Items.IndexOf(item);
if (index != selected)
{
state = checkedListBox1.GetItemCheckState(checkedListBox1.Items.IndexOf(item)).ToString();
if (state == "Checked")
checkedList.Add(item.ToString());
else
uncheckedList.Add(item.ToString());
}
}
}