0

I have a gridview. the rows are added dynamically

Protected Sub btnAddCustomer_Click(sender As Object, e As EventArgs) Handles btnAddCustomer.Click

    Dim dtSource As New DataTable
    dtSource = CType(ViewState("dtSource"), DataTable)
    Dim dr As DataRow = dtSource.NewRow()
    dr("Id") = DropDownList3.SelectedIndex
    dr("Name") = DropDownList3.SelectedItem
    dtSource.Rows.Add(dr)
    ViewState("dtSource") = dtSource
    GridView1.DataSource = dtSource
    GridView1.DataBind()

    GridView1.HeaderRow.Cells(1).Text = "ID"
    GridView1.HeaderRow.Cells(2).Text = "NAME"

End Sub

Each row has a delete image button, and when it is clicked it fires the Code:

    Protected Sub GridVeiw1_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GridView1.RowCommand

    If ViewState("dtSource") IsNot Nothing Then

        Dim dtSource As New DataTable
        Dim drCurrentRow As DataRow = Nothing
        Dim rowIndex As Integer = Convert.ToInt32(e.CommandArgument)
        dtSource = DirectCast(ViewState("dtSource"), DataTable)
        If dtSource.Rows.Count > 0 Then
            dtSource.Rows.RemoveAt(rowIndex)
            drCurrentRow = dtSource.NewRow()
            dtSource.AcceptChanges()
            ViewState("dtSource") = dtSource
            GridView1.DataSource = dtSource
            GridView1.DataBind()
        End If
    End If

End Sub

The delete procedure is not working!!! Any suggessions Please?


I read the question regarding How to delete a row in GV, but it is not helping because am not deleting from GV but from DataTable that contains the data for the GV

Masarwa
  • 43
  • 8
  • It appears to me that you are removing the row from the Gridview but not actually deleting it from the database. – TrevorBrooks Aug 28 '17 at 21:09
  • Possible duplicate of [How to delete a row from GridView?](https://stackoverflow.com/questions/592106/how-to-delete-a-row-from-gridview) – TrevorBrooks Aug 28 '17 at 21:13
  • As you see, am not using an outside database (like mssql). instead of that am using ViewState("dtSource") to save and preserve the GridView1 rows for later use. I convert the ViewState to DataTable, delete the row from the DataTable and then save the new DataTable into the ViewState. I noticed that the number of rows in the DataTable and ViewState is decreasing after the deletion. but After The SUB ends, the number of rows is back to previous number (increased by one) – Masarwa Aug 29 '17 at 09:36
  • I found that deleting the row using the delete image implemented in it was not working. I added a button outside the gridview with the same script above, and it worked for me. Any ideas why it happens? – Masarwa Sep 14 '17 at 11:55

0 Answers0