Matt James
Matt James

Reputation: 9

How can I delete the selected row in GridView control in ASP.net code page?

I have the following VB code in the ASP.net code page, when I click on the delete link button it deletes every row in the GridView. Is it possible to delete the selected row only?

    Protected Sub grvPos_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles grvPos.RowDeleting
    Dim cs As String
    Dim con As iDB2Connection
    Dim sql As String
    Dim cmd As iDB2Command
    Dim valDate As Integer
    Dim portCode As String
    Dim secCode As String

    For Each gr As GridViewRow In grvPos.Rows

        valDate = grvPos.DataKeys(gr.RowIndex).Values("VALN_DATE")
        portCode = grvPos.DataKeys(gr.RowIndex).Values("PORT_CODE").ToString()
        secCode = grvPos.DataKeys(gr.RowIndex).Values("SEC_CODE").ToString()

        cs = ConfigurationManager.ConnectionStrings("ConnectionStringDB2").ConnectionString
        con = New iDB2Connection(cs)
        sql = "DELETE FROM OPTR_POS_FIX WHERE (VALN_DATE = @valDate) AND (PORT_CODE = @portCode) AND (SEC_CODE = @secCode)"
        cmd = New iDB2Command(sql, con)
        cmd.Parameters.AddWithValue("@valDate", valDate)
        cmd.Parameters.AddWithValue("@portCode", portCode)
        cmd.Parameters.AddWithValue("@secCode", secCode)

        Try
            Using con
                con.Open()
                cmd.ExecuteNonQuery()

            End Using

        Catch ex As Exception
            Throw

        End Try
    Next
End Sub

I appreciate any help Thanks in advance

Upvotes: 0

Views: 55

Answers (2)

serges_newj
serges_newj

Reputation: 815

The For Each operator in this code iterates by all rows of the grid. Instead of that you have to get only selected row.

So just remove For Each - Next loop, and add the line

GridViewRow gr = grvPos.Rows[e.RowIndex];

UPD. You're right, in vb.net syntax it will be:

Dim gr As GridViewRow
gr = grvPos.Rows(e.RowIndex)

Upvotes: 1

Matt James
Matt James

Reputation: 9

Thanks I have changed the code in order to function.

    Dim gr As GridViewRow

    gr = grvPos.Rows(e.RowIndex)

Upvotes: 0

Related Questions