Raise Server-Side Click Event of CheckBox in a DataGrid Template Column

yuzhangqi發表於2011-01-04

In an ASP.Net web page, there is a GridView control to show data retrieved from the database. And there is a CheckBox control in the template column of the GridView. When user click on the CheckBox to select/unselect the row on the gridview, and highlight the selected rows.

Problem
You need to respond to the checkbox change event, and know which check box on which row fired the event. The checkbox does not automatically call the datagrid's ItemCommand, so how can we access the datagridItem that represents the row we're clicking?

Solution

In the page code behind file, create a Sub that matches the checkbox changed signature. It's important that the method be declared public or protected.

Protected Sub Check_Clicked(ByVal sender As Object, ByVal e As EventArgs)

End Sub

In the aspx page, modify the checkbox tag by adding the OnCheckedChanged attribute, and setting it to the name of the sub that you just created above. You'll also need autopostback set to true.

<ItemTemplate>
<asp:CheckBox id="CheckBox1" runat="server" AutoPostBack="True" OnCheckedChanged="Check_Clicked">asp:CheckBox
>
>

Now when the checkbox is clicked, the Check_Clicked event will be fired.
That's great, but the signature for the Checkbox_Clicked event does not give us immediate access to the datagridItem like the familiar ItemCommand signature does, so we've got a bit more to do.
It turns out that the checkbox's NamingContainer property evaluates to the datagridItem that we are seeking. Add the following code to the Check_Clicked procedure, and you're home free.

Protected Sub Check_Clicked(ByVal sender As Object, ByVal e As EventArgs)
Dim ck1 As CheckBox = CType(sender, CheckBox)
Dim dgItem As DataGridItem = CType(ck1.NamingContainer, DataGridItem)
'now we've got what we need! Label1.Text = "You selected row " & dgItem.Cells(0).Text
End Sub

References

http://geekswithblogs.net/sgreenberger/archive/2004/11/12/14871.aspx?Pending=true

[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/13651903/viewspace-1044086/,如需轉載,請註明出處,否則將追究法律責任。

相關文章