Deleting rows from a datagrid

J

Junkguy

I'm having difficulty deleting rows from a datagrid. I want to put a "delete"
button on a form and achieve the same functionality as hitting the "delete"
key on the keyboard for the selected row of a datagrid.

I really want to do it generically so I have subclassed datagrid and made my
own delete row method but I can only get it to work for datasources that are
datatables or dataviews.

Specifically when the datasource is a DataSet I cannot figure out how to make
it work. The code works when the datasource is a DataTable or DataView:

public void deleteCurrentRow()
{
if (!this.ReadOnly)
{
if (this.DataSource is DataTable)
{
DataTable dt = (DataTable) this.DataSource;
dt.DefaultView.Delete(this.CurrentRowIndex);
}
else if (this.DataSource is DataView)
{
((DataView) this.DataSource).Delete(this.CurrentRowIndex);
}

}
}

But trying to delete the current row from a DataSet as the DataSource seems
impossible without knowing the table name. In addition, even if we know the
table name of the DataSet, the row in the DataSet Table does not correspond to
the CurrentRowIndex if the DataGrid is sorted.

I have looked and looked, but cannot find any info to clue me in. What is
frustrating to me is that the DataGrid is able to figure it out for itself.
Somehow, it knows what to delete when you hit the "DELETE" key on the
keyboard- but there is no method in DataGrid to clue me in. I become
increasingly frustrated that these form components can do things that I cannot
and refuse to allow me access to their innards to achieve the same
funtionality. I cannot understand why DataGrids do not have an accessable
DeleteRow method.

Anyway, rant aside, if I don't get an answer I'm going to cheat by sending a
SendKeys.Send("{DELETE}"), but I really don't want to do this.

Thanks in advance,
 
C

Chris Taylor

Hi,

You could use the CurrencyManager, the following code should work for most
if not all bindings. This works with a DataSet, DataView and DataTable. If
the DataSet has not been drilled down to a DataTable the cy.List is
DataViewManager returns true preventing the attempt at deleting the row. As
you drill down the DataMember is set to the current DataTable so the correct
CurrencyManager for the current binding is retrieved.

CurrencyManager cy = (CurrencyManager)BindingContext[DataSource,
DataMember];
if ( !(cy.List is DataViewManager) && ( cy.Count > 0 ) )
{
cy.RemoveAt( CurrentRowIndex );
}

Hope this helps

Chris Taylor
 

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