Setting a value in DataTable fires SelectedIndexChanged event
I have a listbox1
which is bound to a DataTable
named Notes
, the line on which I set value in cell of DataTable changes listBox1.SelectedIndex = -1
then again set listBox1.SelectedIndex
to original value and finishes. Hence that line calls listBox1_SelectedIndexChanged
event twice.
Instead it should not even call that event. How to solve this problem?
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
dataSet11.Notes开发者_如何学C.Rows[listBox1.SelectedIndex]["Text"] = richTextBox1.Text;
//this line fires listBox1_SelectedIndexChanged event
//with listBox1.SelectedIndex = -1
//then it changes listBox1.SelectedIndex back to original value before complete execution, and calls the even again
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
Temporarily remove the SelectedIndexChanged handlers
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
listBox1.SelectedIndexChanged -= listBox1_SelectedIndexChanged;
if (listBox1.SelectedIndex != -1)
{
dataSet11.Notes.Rows[listBox1.SelectedIndex]["Text"] = richTextBox1.Text;
//this line fires listBox1_SelectedIndexChanged event
//with listBox1.SelectedIndex = -1
//then it changes listBox1.SelectedIndex back to original value before complete execution, and calls the even again
}
listBox1.SelectedIndexChanged += listBox1_SelectedIndexChanged;
}
You can use a trigger boolean field for this:
private TextBox_OntextChanged(object sender, EventArgs args)
{
this.supressEvents = true;
//Do your stuff here
this.supressEvents = false;
}
private void ListBox_OnSelectionChanged(object sender, EventArgs args)
{
if (this.supressEvents)
{
return;
}
//Do your stuff here
}
精彩评论