Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I tell if a DataGrid's current row has changed and whether the user is on the AddNew row?

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 are 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");
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter