We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

new record and selection

I'm adding new record in DataTable by my program - not internally in the grid. This table is as DataSource for a Grid. How can I find index of newly added row and select this record in a Grid? Thank you

4 Replies

Administrator September 19, 2003 03:13 PM UTC

If you have grid.EnableAddNew = false, then teh last row will be grid.model.RowCount. So, you could try: grid.CurrentCell.MoveTo(grid.model.RowCount, 1); If this does not work, then also call grid.Focus() and set grid.ForceCurrentCellMoveTo = true; to see if that handles it. If you have EnableAddNew = true, then the row should be one less than the RowCount.

SA sahon September 20, 2003 04:14 AM UTC

it doesn't work with sorting in my grid > If you have grid.EnableAddNew = false, then teh last row will be grid.model.RowCount. So, you could try: > > grid.CurrentCell.MoveTo(grid.model.RowCount, 1); > > > If this does not work, then also call grid.Focus() and set grid.ForceCurrentCellMoveTo = true; to see if that handles it. > > If you have EnableAddNew = true, then the row should be one less than the RowCount.

Administrator September 20, 2003 05:39 AM UTC

If you are sorting, then you will have to find the new row in the sorted grid. If your grid displays a primary key column, you can use that key and the grid's support for Find to locate the row. If you do not have a primary key, then you could still use this method, but the located row may not be the new one. Attached is a lttle sample. Another way you can do this that will work for any IBindingList DataSource whether or not there is a primary key, is to use the IBindingList.ListChanged event. In the sample, if you replace the button_click code and add a ListChanged handler as below, that will also position the current cell.
private void cm_ListChanged(object sender, ListChangedEventArgs e)
{
	if(e.ListChangedType == ListChangedType.ItemAdded)
	{
		Console.WriteLine(e.NewIndex);
		this.gridDataBoundGrid1.Focus();
		this.gridDataBoundGrid1.CurrentCell.MoveTo(e.NewIndex+1,1);  
}

private void button1_Click(object sender, System.EventArgs e)
{
	CurrencyManager cm = (CurrencyManager)this.BindingContext[dt];
	((IBindingList)cm.List).ListChanged += new ListChangedEventHandler(cm_ListChanged);

	DataRow dr = dt.NewRow();
	dt.Rows.Add(dr);

	((IBindingList)cm.List).ListChanged -= new ListChangedEventHandler(cm_ListChanged);
}

SA sahon September 20, 2003 06:07 AM UTC

works perfectly, thank you
Loader.
Live Chat Icon For mobile
Up arrow icon