tags:

views:

731

answers:

2

Hello,

I have a DataGridView which is bound to a collection of objects.

I want to make a Delete button on a form so a user could delete selected row.

But there is a problem if a new row (the special last row in the grid) is selected. If I select the new row and then try to click Delete button, the grid loses its focus and changes the selected row! It makes the the last row selected (the one before the new row). So in Delete button handler, there is another row is selected already, not a new row!

How can I solve this problem, other than hiding that special new row (AllowUserToAddRows = false) and making my own "Add" button and code for it?

+1  A: 

You could disable the Delete button when an invalid row (i.e. the special new row) is selected

Julien Poulin
very nice decision! Thank you!
nightcoder
you're welcome :)
Julien Poulin
A: 

Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click

    Dim gr As New DataGridViewRow
    For Each gr In DataGridView1.SelectedRows
        ds.Tables(0).Rows(gr.Index).Delete()
    Next
    ds.AcceptChanges() ' Accept Changes
    DataGridView1.Rows.Clear()
    lbltest.Text = ""
    calldata(ds) ' this function is as follow
    'Public Function calldata(ByRef DS As DataSet)
    '    Dim i As Integer = 0
    '    Dim dr As DataRow
    '    Dim dc As DataColumn
    '    For Each dr In DS.Tables(0).Rows  'dt.Rows
    '        Dim j As Integer = 0
    '        DataGridView1.Rows.Add()
    '        For Each dc In DS.Tables(0).Columns 'dt.Columns
    '            DataGridView1.Rows(i).Cells(j).Value = dr(dc).ToString()
    '            lbltest.Text = lbltest.Text & " : " & dr(dc).ToString()
    '            j = j + 1
    '        Next
    '        i = i + 1
    '    Next

    'End Function
    ' the above code only update your dataset not actual data
End Sub