Geeks With Blogs
IDeploy adventures of a geek without a parachute

This post has generated lots of comments and over 1,500 hits per month, I hope that it is helpful to you. Before you comment on the post, I need to point out that this is just a weblog. Please use the following guidelines when considering comments.

1) If you find my solution useful, or have trouble making it work, please post comments.
2) If you have a different or related problem, I suggest you try
experts exchange, which is a dedicated help forum.
3) If you would like to send me an email directly, go
here. I'll try to answer questions, but please understand that my time is limited, so I may not be able to get back to you right away.

-Scott :)

I'm currently working on an ASP.NET project that uses a datagrid with several checkboxes in the item templates, and we wanted to use the checkbox click event to modify appropriate data.

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?

After some experimenting, here's what I believe to be the best 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.

   <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


Posted on Friday, November 12, 2004 12:11 AM Tips | Back to top

Comments on this post: How to use a checkbox in a datagrid template column.

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Scott G. | Powered by: