views:

30

answers:

2

I have a DataGridView that is bound to a DataSet and I allow someone to remove a row from the table and I remove the row from the set. My code looks like this:

ds.Tables(0).Rows(dgCourseList.SelectedRows(0).Index).Delete()

My problem I found is if the grid gets sorted the index of the rows no longer corresponds to the indexes in the DataSet. As a result the wrong rows get removed from the set.

Can I solve this problem with maybe having to sort the DataSet on some sort event of the DataGridView?

A: 

I think you'll want to use the CurrencyManager to handle this.

Here's a quick article explaining the concept: http://support.microsoft.com/kb/817247

' Get the Currency Manager by using the BindingContext of the DataGrid '
Dim cm As CurrencyManager = CType(Me.BindingContext(DataGrid1.DataSource, DataGrid1.DataMember), CurrencyManager)

' Retrieve the default DataView of the DataGrid '
Dim dv As DataView = CType(cm.List, DataView)

' Use Currency Manager and DataView to retrieve the Current Row '
Dim dr As DataRow
dr = dv.Item(cm.Position).Row

' Display the Current Row Data '
TextBox1.Text = dr(0).ToString
TextBox2.Text = dr(1).ToString

Using the CurrencyManager, you can retrieve the original state and go from there.

Cheers, JS

Johnny Saxon
I have read the article and I put the code in and it still doesn't work. The only thing i do differently is my line read: ds.Tables(0).Rows.Remove(dr) Do you have to sort just like they do in the article? or can you sort by the standard clicking on the column headers.
Tim
I finally figured out what going on. I have made my program to allow a user to right click a row and a context menu gives them the option to delete the row. If I right click a row the Currency Manager doesnt recognize the selected row changing. If I left click the row first then right click it does recognize the change in row and deletes the correct one.
Tim
A: 

I haven't tested this but try the following assuming you have the DataKeys setup properly:

ds.Tables(0).Rows.Remove(ds.Tables(0).Rows.Find(dgCourseList.DataKeys(dg.SelectedIndex)))

EDIT: Based on you specifying that you are using a DataGridView which is a winforms app (I was assuming a webforms app) then you could try:

ds.Tables(0).Rows.Remove(ds.Tables(0).Rows.Find(DirectCast(dg.SelectedRows(0).DataBoundItem, DataRowView).Row))

EDIT 2: Updated because I think the cast was wrong... still untested though.

Kelsey
This gives me a MissginPrimaryKeyException. Which is strange because I know there's a primary key defined in the table.
Tim
Figured out how to set the primary key in the DataSet. Now it removes the correct row from the set and grid, but when I commit, it does not delete the entry from the database.
Tim