Search code examples
asp.netvb.netgridviewvisual-studio-2005

Programmatically update a bound checkbox in a GridView using an asp:ButtonField in ASP.NET 2005


The GridView is bound to an Access Table, but I want to update the checkbox using the asp:ButtonField. The best I've been able to do is replace the checkbox with a string value. Below is the code I have now:

Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
    If e.CommandName = "check" Then
        'Enable Editing on the GridView
        GridView1.EditIndex = GridView1.SelectedIndex
        'Assign value to the row selected
        Dim index As Integer = Convert.ToInt32(e.CommandArgument)
        'Assign selected gridview row
        Dim selectedRow As GridViewRow = GridView1.Rows(index)
        'Assign checkbox cell as table cell
        Dim selectedCell As TableCell = selectedRow.Cells(0)

        'Assign a value to the checkbox, **but instead is replacing the checkbox**
        selectedCell.Text = "True"
    End If
End Sub

Solution

  • I think you need to use .FindControl().

    The GridViewCell is not the same thing as a CheckBox control inside it. You code should probably look more like:

    Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
        If e.CommandName = "check" Then
            'Enable Editing on the GridView
            GridView1.EditIndex = GridView1.SelectedIndex
            'Assign value to the row selected
            Dim index As Integer = Convert.ToInt32(e.CommandArgument)
            'Assign selected gridview row
            Dim checkBox As CheckBox = GridView1.Rows(index).FindControl("checkBoxIdGoesHere")
    
            checkBox.Checked = true 'or false or whatever based on your command.
        End If
    End Sub