使用ASP.NET 2005中的asp:ButtonField以编程方式更新GridView中的绑定复选框

时间:2012-01-06 15:01:00

标签: asp.net vb.net gridview visual-studio-2005

GridView绑定到Access Table,但我想使用asp:ButtonField更新复选框。我能做的最好的事情是用一个字符串值替换复选框。以下是我现在的代码:

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

感谢任何和所有帮助!

2 个答案:

答案 0 :(得分:4)

我认为您需要使用.FindControl()

GridViewCell与其中的CheckBox控件不同。您的代码应该看起来更像:

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

答案 1 :(得分:1)

我在GridViews中访问控件时遇到了一些问题。一个月前我解决了类似的问题。假设您的复选框控件是该单元格中唯一的东西,您可以尝试这样的事情:

'Assign a value to the checkbox
CType(GridView1.Rows(index).Cells(0).Controls(0), CheckBox).Checked = True

试一下,看看它是否有效。如果没有,请回复,我们可以再看看。