Saturday, September 20, 2014

ASP.NET GridView RowCommand Event Firing Twice

This issue happened when I migrated an asp.net 3.5 website to an asp.net 4.5 website. Upon clicking Add or Delete linkbuttons in the GridView, the RowCommand event fires twice. After googling for hours, I found a solution that is to remove the Handles GridView1.RowCommand in the event declaration.
The code below does not work (event fires twice)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) _
        Handles GridView1.RowCommand
        If e.CommandName.Equals("AddNew") Then
            Dim txtNewName As TextBox
            txtNewName = CType(GridView1.FooterRow.FindControl("txtNewName"), TextBox)
            Dim cmbNewGender As DropDownList
            cmbNewGender = CType(GridView1.FooterRow.FindControl("cmbNewGender"), DropDownList)
            Dim txtNewCity As TextBox
            txtNewCity = CType(GridView1.FooterRow.FindControl("txtNewCity"), TextBox)
            Dim txtNewState As TextBox
            txtNewState = CType(GridView1.FooterRow.FindControl("txtNewState"), TextBox)
            Dim cmbNewType As DropDownList
            cmbNewType = CType(GridView1.FooterRow.FindControl("cmbNewType"), DropDownList)
 
            Dim objCustomer As New CustomerCls()
            objCustomer.InsertCustomer(txtNewName.Text, cmbNewGender.SelectedValue, txtNewCity.Text, txtNewState.Text, cmbNewType.SelectedValue)
            FillCustomerInGrid()
        End If
 
    End Sub

The code below works (Handles GridView1.RowCommand removed)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) 
        If e.CommandName.Equals("AddNew") Then
            Dim txtNewName As TextBox
            txtNewName = CType(GridView1.FooterRow.FindControl("txtNewName"), TextBox)
            Dim cmbNewGender As DropDownList
            cmbNewGender = CType(GridView1.FooterRow.FindControl("cmbNewGender"), DropDownList)
            Dim txtNewCity As TextBox
            txtNewCity = CType(GridView1.FooterRow.FindControl("txtNewCity"), TextBox)
            Dim txtNewState As TextBox
            txtNewState = CType(GridView1.FooterRow.FindControl("txtNewState"), TextBox)
            Dim cmbNewType As DropDownList
            cmbNewType = CType(GridView1.FooterRow.FindControl("cmbNewType"), DropDownList)
 
            Dim objCustomer As New CustomerCls()
            objCustomer.InsertCustomer(txtNewName.Text, cmbNewGender.SelectedValue, txtNewCity.Text, txtNewState.Text, cmbNewType.SelectedValue)
            FillCustomerInGrid()
        End If
 
    End Sub

0 comments:

Post a Comment