How can I tell if the current row has changed and whether I am on the AddNew row or not

Platform: WinForms| Category: Datagrid

The DataGrid’s CurrentCellChanged event is hit even if you just change cells in the current row. If you want an event that is only hit when you change rows, then you have to look at the binding manager. This object has both a CurrentChanged event and a PositionChanged event which are hit when you change rows.

To decide whether you are on the AddNew row or not, you can again use the binding manager and compare the number of rows it returns with the number of rows in your data table. Below is some code snippets showing how you might get at this information.

private System.Windows.Forms.DataGrid dataGrid1;
private BindingManagerBase bindingManager;

private void Form1_Load(object sender, System.EventArgs e)
{
	// Creating connection and command sting 
	string conStr = @'Provider=Microsoft.JET.OLEDB.4.0;data source=C:\northwind.mdb'; 
	string sqlStr = 'SELECT * FROM Employees'; 
	// Create connection object 
	OleDbConnection conn = new OleDbConnection(conStr); 
	// Create data adapter object 
	OleDbDataAdapter da = new OleDbDataAdapter(sqlStr,conn); 

	// Create a dataset object and fill with data using data adapter’s Fill method 
	DataSet ds = new DataSet(); 
	da.Fill(ds, 'Employees'); 
	dataGrid1.DataSource = ds.Tables['Employees'];
	bindingManager =  this.BindingContext[dataGrid1.DataSource];
	bindingManager.PositionChanged += new System.EventHandler(RowChanged);
}

private void RowChanged(object sender, System.EventArgs e)
{
	Console.WriteLine('RowChanged ' + bindingManager.Position.ToString() );
	bool lastRow = bindingManager.Count > ((DataTable)dataGrid1.DataSource).Rows.Count;
	
	if(lastRow)
		Console.WriteLine('lastRow');
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.