delete selected rows from a datagrid

G

Guest

I have a datagrid whose datasource is a datatable. I want the user to select
(multiple) rows in the datagrid, press a button and have the selected rows
deleted. Iterating through the rows in the datagrid and testing to see if
each is selected and then deleting the associated datarow from the datatable
is probably inefficient but nevertheless doesn't work because the selected
rows in the datagrid are reset as soon as the first record is deleted from
the datatable. Is there an obviously correct method for doing this?
 
J

Jeffrey Tan[MSFT]

Hi Richard,

Based on my understanding, you want to delete several selected rows fromt
the datagrid at one time.

Yes, because of databinding, deleting one row in underlying datasource will
make DataGrid repopulates itself, and all the rows' row number behind the
deleting row will decrease one.

For this issue, I think we may use a ArrayList to store all the initial
selected row number, when deleting the row, each row number decrease the
already deleted row count. Sample code like this:

private void button1_Click(object sender, System.EventArgs e)
{
ArrayList al=new ArrayList();
CurrencyManager cm
=(CurrencyManager)dataGrid1.BindingContext[this.ds.Tables["your table"]];
for(int i=0;i<cm.Count;i++)
{
if(this.dataGrid1.IsSelected(i))
{
al.Add(i);
}
}

for(int i=0;i<al.Count;i++)
{
int row=(int)al;
this.ds.Tables["your table"].Rows.RemoveAt(row-i); //row number
decrease already deleted row count
}
}
=======================================
Please apply my suggestion above and let me know if it helps resolve your
problem.

Thank you for your patience and cooperation. If you have any questions or
concerns, please feel free to post it in the group. I am standing by to be
of assistance.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
J

Jeffrey Tan[MSFT]

You are welcome, if you need further help, please feel free to tell me,
thanks

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top