我有3个列表框,当我选择了三件事时,单击“删除”按钮,它删除了第一个列表框中的文本,但是给出一个例外,说值-1对索引无效。这是我当前的代码:
lstBoxOne.Items.RemoveAt(lstBoxOne.SelectedIndex);
lstBoxTwo.Items.RemoveAt(lstBoxTwo.SelectedIndex);
lstBoxThree.Items.RemoveAt(lstBoxThree.SelectedIndex);
想知道他们是否可以通过单击按钮删除所有三个选定的文本
编辑:我现在已经放满了期望的图像 Full exception
编辑2:这是带有完整代码的示例
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void LstBoxOne_SelectedIndexChanged(object sender, EventArgs e)
{
var deleteD = lstBoxOne.SelectedIndex;
lstBoxTwo.SelectedIndex = deleteD;
lstBoxThree.SelectedIndex = deleteD;
}
private void BtnInsert_Click(object sender, EventArgs e)
{
lstBoxOne.Items.Add(this.txtOne.Text);
lstBoxTwo.Items.Add(this.txtTwo.Text);
lstBoxThree.Items.Add(this.txtThree.Text);
this.txtOne.Focus();
this.txtOne.Clear();
this.txtTwo.Focus();
this.txtTwo.Clear();
this.txtThree.Focus();
this.txtThree.Clear();
}
private void BtnDelete_Click(object sender, EventArgs e)
{
lstBoxOne.Items.RemoveAt(lstBoxOne.SelectedIndex);
lstBoxTwo.Items.RemoveAt(lstBoxTwo.SelectedIndex);
lstBoxThree.Items.RemoveAt(lstBoxThree.SelectedIndex);
}
private void LstBoxTwo_SelectedIndexChanged(object sender, EventArgs e)
{
var deleteD = lstBoxTwo.SelectedIndex;
lstBoxOne.SelectedIndex = deleteD;
lstBoxThree.SelectedIndex = deleteD;
}
private void LstBoxThree_SelectedIndexChanged(object sender, EventArgs e)
{
var deleteD = lstBoxThree.SelectedIndex;
lstBoxOne.SelectedIndex = deleteD;
lstBoxTwo.SelectedIndex = deleteD;
}
}
}
}
答案 0 :(得分:1)
问题是由于SelectedIndexChanged
上的lstBoxOne
事件引起的。
在BtnDelete_Click
内,当您从lstBoxOne
中删除所选项目时,这会导致lstBoxOne.SelectedIndex
发生变化。这导致LstBoxOne_SelectedIndexChanged
在之前触发,该项目已从lstBoxTwo
和lstBoxThree
中删除。当LstBoxOne_SelectedIndexChanged
完成并返回到BtnDelete_Click
时,lstBoxTwo.SelectedIndex
和lstBoxThree.SelectedIndex
均为-1
,并且Exception
由于传递{{1}而发生}到-1
。
RemoveAt
解决此问题的一种简单方法是在尝试删除任何项目之前存储每个private void LstBoxOne_SelectedIndexChanged(object sender, EventArgs e)
{
var deleteD = lstBoxOne.SelectedIndex;
lstBoxTwo.SelectedIndex = deleteD;
lstBoxThree.SelecteIndex = deleteD;
}
private void DeleteBtn_Click(object sender, EventArgs e)
{
lstBoxOne.Items.RemoveAt(lstBoxOne.SelectedIndex); //This line triggers the SelectedIndexChanged event on lstBoxOne.
// By the time we get back to this function, lstBoxTwo and lstBoxThree have had
// their SelectedIndex set to -1. That is what is causing the exception to occur.
lstBoxTwo.Items.RemoveAt(lstBoxTwo.SelectedIndex); //Ooops! lstBoxTwo.SelectedIndex was set to -1 in LstBoxOne_SelectedIndexChanged.
}
的选定索引。另外,请检查ListBox
来保护自己。
-1