I am facing an issue with dataGridView BindingContextChanged event firing. I have 2 datagridview in form and BindingContextChanged event implemented for both the grids.
On BindGrid method grid1 bound first with data source but BindingContextChanged event of grid2 fires first then grid1, then after grid2 bound with other data source but grid2 BindingContextChanged event does not fire. I have no clue why this is happening, I need each BindingContextChanged event should fire after respective grid data source assignment. Please help me to fix this issue.
below is the sample code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.dataGridView1.BindingContextChanged += new System.EventHandler(this.dataGridView1_BindingContextChanged);
this.dataGridView2.BindingContextChanged += new System.EventHandler(this.dataGridView2_BindingContextChanged);
}
private void btnBind_Click(object sender, EventArgs e)
{
BindGrid();
}
protected void BindGrid()
{
DataTable dt1 = new DataTable();
dt1.Columns.Add("ID", typeof(int));
dt1.Rows.Add(1);
dt1.Rows.Add(2);
dt1.Rows.Add(3);
BindingSource dataSource = new BindingSource(dt1, null);
dataGridView1.DataSource = dataSource;
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Rows.Add(1);
dt.Rows.Add(2);
dt.Rows.Add(3);
BindingSource dataSource1 = new BindingSource(dt, null);
dataGridView2.DataSource = dataSource1;
}
private void dataGridView1_BindingContextChanged(object sender, EventArgs e)
{
// Continue only if the data source has been set.
if (dataGridView1.DataSource == null)
{
return;
}
}
private void dataGridView2_BindingContextChanged(object sender, EventArgs e)
{
// Continue only if the data source has been set.
if (dataGridView2.DataSource == null)
{
return;
}
}
}
.Designer.csfile of your Form:this.Controls.Add(this.dataGridView1);is probably inserted afterthis.Controls.Add(this.dataGridView2);. So, just invert it. -- Why are you handling this event? As mentioned, any other Control can cause it to raise. What is it for? - Jimi