Reputation: 1390
I have a three columns in a DataGridView which the user can enter any combination of either a time, start and finish. Upon changing any of these, the other two are calculated.
My thought was to use the DataTable.ColumnChanged event handler. Unsurprisingly, calculating the value within the ColumnChanged handler causes the event handler to fire again and end up in an infinite loop.
I've tried various ways of setting flags and removing the event handler temporarily, but no matter what I do, the event continues to fire repeatedly.
Can anyone provide ideas on how to ensure the event only fires on the first change or alternatively, doesn't process the same code (and subsequently cause the event to fire again)?
many thanks Matt
Upvotes: 1
Views: 685
Reputation: 6472
I tried your way and it works Perfect. Here's the code:
DataTable dt;
bool SilenceMode;
private void Form1_Load(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add("A");
dt.Columns.Add("B");
dt.ColumnChanged += ColChange;
dataGridView1.DataSource = dt;
}
void ColChange(object sender, DataColumnChangeEventArgs e )
{
if (!SilenceMode)
{
SilenceMode = true;
//******************
//Here edit DataTable Without infinity loop
string colNameToChange = e.Column.ColumnName == "A" ? "B" : "A";
e.Row[colNameToChange] = e.ProposedValue;
//******************
SilenceMode = false;
}
}
But I think it is better to implement it in UI (events of the DataGridView).
Upvotes: 2