IDeploy

adventures of a geek without a parachute

  Home  |   Contact  |   Syndication    |   Login
  35 Posts | 1 Stories | 41 Comments | 207 Trackbacks

News

Archives

Post Categories

Image Galleries

________

Articles

Blogroll

Humor

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.

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?

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.

<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

 

posted on Friday, November 12, 2004 12:11 AM

Feedback

# re: How to use a checkbox in a datagrid template column. 11/18/2004 3:11 PM Hermes
This post was short but sweet. Helped a lot in the project I'm working on. Great work...

Thanks again,
Hermes

# re: How to use a checkbox in a datagrid template column. 11/23/2004 8:23 AM endo
I am still stuck here because the dgItem.Cells(0).Text is always null for some reason. Any ideas why I would get this? Here's some of my code:

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!
Response.write ("You selected row " & dgItem.Cells(0).Text)
End Sub



-----------------------------------------------------------

<asp:TemplateColumn HeaderText="Active">
<ItemTemplate>
<asp:CheckBox runat="server" AutoPostBack=True ID="tbReviewed" Checked='<%# DataBinder.Eval(Container.DataItem, "ReviewedField") %>' OnCheckedChanged="Check_Clicked" />
</ItemTemplate>
</asp:TemplateColumn>


# re: How to use a checkbox in a datagrid template column. 12/2/2004 10:56 AM Rainer
I've done exactly like described above, but for any reason the "Check_Clicked" - event is not been fired. Do I have to register it manually and when, where or how ?

# re: How to use a checkbox in a datagrid template column. 12/7/2004 4:00 AM tejasvi
Good information

# re: How to use a checkbox in a datagrid template column. 12/16/2004 11:10 AM Olivia
I did the exactky the same thing in the example. my check_clicked event does not fire? does anyone have the solution for that?Thank you!!!!

# re: How to use a checkbox in a datagrid template column. 12/23/2004 1:19 AM Ganesh
Olivia,

ensure that you have set the "AutoPostBack" property of the checkbox to"True"

let me know at : ganesh_ha@yahoo.co.in

# re: How to use a checkbox in a datagrid template column. 12/29/2004 10:24 PM Scott
Endo,
The code in the posting does not include data for the grid, I left that part up to the reader.

"dgItem.Cells(0).Text" in the example refers to the first cell in my datagrid row.

Once you havce the DataGridItem for your grid, you can get to the individual cells using the .Cells(index).Text construct.

Hope that helps..use the contact link to on this page to email me if you still can't get it working.

# re: How to use a checkbox in a datagrid template column. 1/5/2005 12:10 PM Olivia
I did everything in the example (including set the AutoPostBack to True).The event still didn't fire. I changed the EnableViewState Property of the Datagrid to False. The event then fired when I check the box,however when I unchecked the box, the event stop firing again. Anyone has any idea what it could possibly be the problem?
Thanks
my email: Olivia919@hotmail.com

# re: How to use a checkbox in a datagrid template column. 1/6/2005 6:24 PM gordon
Works Great !!

# re: How to use a checkbox in a datagrid template column. 1/9/2005 9:08 AM Vish
Can some one put the C# code for the above as I am a learning

# re: How to use a checkbox in a datagrid template column. 1/11/2005 11:02 AM Andy Foster
Hi,
Neat code - thanks, but I have a question.

How do I detect in the Check_Clicked event handler, whether the check box was checked or not.

I suppose I want somthing like:-

dgItem.Cells(1).controls(0).ClientID.Checked

..but I can't seem to find how to reference the checkbox. I've tried the ClientID, ID properties, but Can't seem to get the syntax...





# Determining the value of the checked property.. 1/12/2005 11:30 PM Scott


Andy,
In this case, it's actually easier than you think to get the checkbox's checked state. The "sender" parameter in the Check_Clicked event is actually the checkbox that triggered the event.

First we cast sender to a checkbox...
Dim ck1 As CheckBox = CType(sender, CheckBox)

then we can evaluate the checked state:
dim fChecked as boolean = ck1.Checked

Alternatively, this could've been done in one line:
dim fChecked as boolean = ctype(sender,Checkbox),Checked


Regards,
Scott


# re: How to use a checkbox in a datagrid template column. 1/14/2005 12:02 PM ASP Senior Developer
This will not work when u use this in a datagrid and try to delete a item using this.
So please dont give such bleedy answers plz

# re: How to use a checkbox in a datagrid template column. 1/14/2005 3:23 PM Scott
"ASP Senior Developer",
If you choose to critique my post, please be kind enough to explain why you think it's "bleedy", and provide a better solution for others.
Alternatively, if you provide contact information, I will be happy to discuss your viewpoint with you.
Although I would not choose to delete an item by selecting a checkbox in the item's row, my own tests confirm that this technique can be used in that scenario. Of course you need to obtain a datakey for the item you want to delete.

# re: How to use a checkbox in a datagrid template column. 1/17/2005 2:15 PM Olivia
of course it works for deleteing an item!!!

# re: How to use a checkbox in a datagrid template column. 1/18/2005 11:27 AM Miguel
"ASP Senior Developer" is bleedy, oops I mean Bloody wrong - not to mention rude as hell. Tell you what brother, yes I mean you 'senior developer', if you are going to post something so negative, have the decency to post a solution that you think will work. Guess what - that's what Blogging means.

# re: How to use a checkbox in a datagrid template column. 1/26/2005 10:06 AM Darren
When I test for the .Checked = true for the checkbox on the postback, it always evaluates as false, irregardless of whether it's checked or not. I test for other properties (id, text) and they are all there. EnableViewState is true as well. Any ideas?

# re: How to use a checkbox in a datagrid template column. 1/26/2005 5:41 PM Scott
Darren,
I'd really need to see your code, but I suspect it's in your databind. The original post was intended to be a quick answer, and admittedly, it does leave some details out. Enough people have had trouble implementing this that I feel it would be helpful to provide full sample code. I'll try to do that in th next day or two. Stay tuned...

# re: How to use a checkbox in a datagrid template column. 1/27/2005 10:26 AM Darren
Scott,
I figured out what it was and I am embarrassed by my negligence, but I will post it here just in case others have made the same silly mistake.

On the OnLoad event of the page, I am doing my datagrid databinding, and I forgot to test for the Page.IsPostBack property, so in essense, I was resetting my datagrid's state before I stepped into my Check_Clicked event. After I moved my datagrid's databinding logic into the If Not Page.IsPostBack statement block, everything worked as you said:

Private Sub Page_Load ...
If Not Page.IsPostBack Then
BindGrid()
End If
End Sub

Just as an FYI, I converted your sample to c#.

Thanks for your great example!

Darren

# re: How to use a checkbox in a datagrid template column. 1/28/2005 4:41 PM Graeme
All's well until I rebind the data during the postback in my page's PreRender sub. At that point, the checkbox that was checked becomes unchecked and the grid therefore never visually changes. I can see that the selected checkbox has been checked in the Check_Clicked sub, but after the databind, it becomes unchecked and that is what is seen in the grid.
I am dynamically building the grid because I don't know what type of dataset I will need to show in the control, so I have to leave it until the PreRender. In the grid's ItemDataBound event, I can see when the various rows are being bound but what can I do to keep the checkbox checked?
Thanks for your help.
graeme.m.weeks@sdc-dsc.gc.ca

# re: How to use a checkbox in a datagrid template column. 2/1/2005 2:56 PM Scott
Graeme, if the checkbox is data bound, you'll need to pdate your data prior to the databind you're doing in prerender. If your chexkbox is not databound, you'll need to manage this somehow (perhaps in the itemdatabound event?).

Scott

# re: How to use a checkbox in a datagrid template column. 2/1/2005 10:50 PM Timothy Allan
This was the EXACT thing that I needed for this app we're doing, nice job, thanks!

-Tim
www.timothyallan.com - free mp3 programming music!

# re: How to use a checkbox in a datagrid template column. 2/3/2005 12:58 AM shruthi
Hi everyone,
i am new here and everything here is very interesting.
i too am facing the same problem of handling the event triggered by the checkboxes in the template column of the data grid. I need the code in C#? can anyone help?? please.........

# re: How to use a checkbox in a datagrid template column. 2/3/2005 12:40 PM MaryU
Thank-you so, so, so much for this post!!! It worked wonderfully for me.

# re: How to use a checkbox in a datagrid template column. 2/7/2005 6:29 AM hexpart
Scott,

your code is working temendously. i tried it in C#. i provide here the code for C# developers:-

=============
protected void Check_Clicked(Object sender, EventArgs e)
{
CheckBox ck1 = (CheckBox) sender;
DataGridItem dgItem = (DataGridItem)ck1.NamingContainer;

//now we've got what we need!

Response.write ("You selected row " + dgItem.Cells[0].Text)
}
=============

But what if I want to access the header item of datagrid. actually, i have a check box in header item and want to take some action when it clicked.

Waiting for a working solution.

Happy Programming.

# re: How to use a checkbox in a datagrid template column. 2/7/2005 9:02 PM singth
Great thanks.

I tried and it works.

Not necessary to have AutoPostBak=true in checkbox attribute. As long as there is a postback event, might be triggered by a button, then it will trigger the _checkedChanged event handler.

# re: How to use a checkbox in a datagrid template column. 2/13/2005 9:04 PM Dan
This is my first .NET page, so please be forgive me -
I tried this and it worked great - thank you.

I am looking for a way to only return the rows for check box's that were clicked without having to parse through every row.

Is there not a way to use the event without having to post the page everytime ? I do not prefer the way it bounces to the top of the page after every checkbox is clicked.

Any help is appreciated - thanks.

# re: How to use a checkbox in a datagrid template column. 2/15/2005 8:17 AM Newbie
Hello, All
Norrmally I would use

<ItemTemplate>
<input type="checkbox" id="mycheck" value='<%DataBinder.Eval(Container.Item,"id_index")%>' />
<ItemTemplate>
To use the values that were checked

Any Concrete Ideas/Experience how can I hande the checked state of the checkbox above ? To check or unckeck checkbox.

Or How can I append value field to
<asp:Checkbox > </asp:Checkbox >
Syntax. Because DataGridItemCollection item
item[index_to_specific_row].FindControl("mycheck");
Does not work
Regards,




# re: How to use a checkbox in a datagrid template column. 2/16/2005 10:43 AM Maxat
thank you for your code
its really helpful,

# re: How to use a checkbox in a datagrid template column. 2/16/2005 5:41 PM DotNetProgrammer
This code was really helpful...Thanks to whoever initiated it & whoever gave solution...

# re: How to use a checkbox in a datagrid template column. 2/21/2005 7:56 AM kranthi
I am having a grid auto pagination as true with check box in template column and submit button . In the click of the submit button, i am saving the status of check boxes. When i check some check boxes and navigates to another page, the view is not saving . Can any give solution how to persist state of check boxes in navigating through pages of grid



# re: How to use a checkbox in a datagrid template column. 2/25/2005 7:03 PM mph
dgItem.Cells(0).Text is always null

# re: How to use a checkbox in a datagrid template column. 2/25/2005 7:04 PM dan
ck1.NamingContainer.ID.ToString gives me
Object reference not set to an instance of an object.



# re: How to use a checkbox in a datagrid template column. 2/28/2005 9:52 AM scott
Not sure why you're getting an invalid reference, but the NamingContainer does not have a unique ID. What did you plan to use it for? There is probably a simple way to get what you need.


# re: How to use a checkbox in a datagrid template column. 2/28/2005 10:43 AM mph
dgItem.Cells(0).Text is always null


# re: How to use a checkbox in a datagrid template column. 3/1/2005 8:53 AM scott
<<dgItem.Cells(0).Text is always null>>
this is specific to *your* data, it depends what's in your grid dgItem.Cells(0) is only an example.

# re: How to use a checkbox in a datagrid template column. 3/1/2005 10:45 AM mph
I'm aware of that. I have a id field that should be returned from this cell and it is not showing up.

# re: How to use a checkbox in a datagrid template column. 3/1/2005 10:50 AM scott
If you want to post or send me your code, I'll take a look at it.

# re: How to use a checkbox in a datagrid template column. 3/3/2005 5:04 PM ucf
Hey Scott, great article!!! Solved one of my problems! Thanks!

# re: How to use a checkbox in a datagrid template column. 3/5/2005 5:50 AM ns
It's great, working fine, but my requirement is to select all the rows which are checked in the datagrid in order to perform some work on those selected records, how can I do it? Thanks in advance.

# re: How to use a checkbox in a datagrid template column. 3/7/2005 7:12 PM JRL
THANK YOU, THANK YOU, THANK YOU!!!

I spent an hour Googling and trying stuff that didn't work before I found your post. Then I got my page working in minutes. Thanks again for the the great post.

JRL

# re: How to use a checkbox in a datagrid template column. 3/7/2005 10:44 PM Red
I can't make it work in C#. Do i have to add an event handler for the Check_Clicked?

Thanks.

# re: How to use a checkbox in a datagrid template column. 3/8/2005 8:56 AM Scott
If you've used the OnCheckedChanged attribute in your aspx, no additional wiring is needed.

# re: How to use a checkbox in a datagrid template column. 3/8/2005 12:14 PM praveen saini
hi Scott,
i used OnChekedChanged event
bt i m getting the event fire 4 that,

pksaini@rediffmail.com

# re: How to use a checkbox in a datagrid template column. 3/8/2005 12:37 PM Scott
Praveen,
I am referring to the OnCheckedChanged attribute in the aspx. Remember C# is case sensitive, so the value of the attribute will need to match the function in your codebehind that you intend to fire.
If you still have trouble,Post the relevant code (ASPX and codebehind), and I'll take a peek.

# re: How to use a checkbox in a datagrid template column. 3/11/2005 12:03 AM mike brady
For those of you having problems getting your event to fire, you are probably rebinding your datagrid before the event gets a chance to fire.

If you cannot check for an ispostback, then place the logic from your page_load in to the page's prerender method.


# re: How to use a checkbox in a datagrid template column. 3/11/2005 9:08 AM James
Nice posting. Helped me a lot with a C# project I'm working on.

# re: How to use a checkbox in a datagrid template column. 3/11/2005 10:59 AM praveen saini
hi scott, i remine all thing bt. nothing getted , so i m forwarding u the code 4 tht pl. tell me wht problem s in it.

===========
<asp:TemplateColumn HeaderText="select">
<ItemTemplate>
<asp:CheckBox id="CheckBox1" runat="server" OnCheckedChanged="on_checked_changed"></asp:CheckBox>
</ItemTemplate>
=================
public void on_checked_changed(object sender, System.EventArgs e)
{
Label1.Text="click";

}

# re: How to use a checkbox in a datagrid template column. 3/11/2005 8:29 PM Chiensey
Hi, can I get some help about the checkbox item checked an be store inside the database?
Please help. Thanks.

Chiensey
chiensey@yahoo.com.sg


# re: How to use a checkbox in a datagrid template column. 3/12/2005 1:24 AM praveen saini
thaks scott
its hapnd, yesterday night it happend , thanks 4 ur g8 suggestion,

bt. SOMETHING REMAIN, in the below code the event got fired,
public void on_checked_changed(object sender, System.EventArgs e)
{
Label1.Text="click";

}

bt. how DID I KNOW THT WHICH CHECKBOX CLICKED OF ITEMS.


# re: How to use a checkbox in a datagrid template column. 3/12/2005 11:32 AM praveen saini
now i completed all thing, just i want tht if i select header check box the below onw automatically select, i m doing this thing, bt i m facing a problem tht , i m unable 2 get the subbordinate checkbox id (control in header checkbox procedure) , how i do it pl. let me know scott



# re: How to use a checkbox in a datagrid template column. 3/14/2005 11:15 PM jay
Hi Scott,

Good source of Information.

I have a question, regarding check box state in the Datagrid, across paging. How to maintain state of the check boxes while user moves from one page to the other.
Is View State can help me in this regard.

And also, in my case, ?I am using databinding in page load event, without checking for the ispostbask flag. I need to do this for certain reasons. In this case how do I do, check all and invert selection on the grid check box column.

# re: How to use a checkbox in a datagrid template column. 3/16/2005 10:55 AM Petro
Hello folks, suppose if I want to iterate thru the entire datagrid to see what was check and what was not chekced. How do I do that?

Thanks in advance,
Petro

# re: How to use a checkbox in a datagrid template column. 3/18/2005 2:32 AM suresh
Good Description

# re: How to use a checkbox in a datagrid template column. 3/22/2005 5:16 AM NO37
Thanx Scott c",)

I've been looking for this kind of solution for days now.
The NamingContainer property was what I was looking for.

Good work !

# re: How to use a checkbox in a datagrid template column. 3/23/2005 12:05 AM Sun
Thanks, scott. It really helped me. sun

# re: How to use a checkbox in a datagrid template column. 3/24/2005 2:10 PM Fernando
Obrigado; Este exemplo me ajudou muito.

# re: How to use a checkbox in a datagrid template column. 3/26/2005 9:17 AM Raed
Hello Scott,

Please, have a look on this code sample (my code).

HTML:
*****
<ItemTemplate>
<asp:CheckBox id="CHK_Select" runat="server" EnableViewState=False AutoPostBack=True OnCheckedChanged="Check_Clicked"></asp:CheckBox>
</ItemTemplate>

CODE BEHIND:
************
protected void Check_Clicked(Object sender, EventArgs e)
{
CheckBox ck1 = (CheckBox) sender;
DataGridItem dgItem = (DataGridItem)ck1.NamingContainer;

//now we've got what we need!
Response.Write ("You selected row " + dgItem.Cells[0].Text);
}

I think this is like your example (using C#) but it does not work.

Please help,
Thanks,
Raed


# re: How to use a checkbox in a datagrid template column. 3/28/2005 12:46 PM Corby Kissler
THANK YOU!

Great piece of code - worked well right into a project we're doing.

Already had the template autopopulating but needed a way to check forr updates to the grid. This worked perfect! Didn't need the autopostback and it actually works better without it round tripping to the server on change event. I can add the rows being updated to an array then read those out when the user clicks on my update button.

Thanks again!

# re: How to use a checkbox in a datagrid template column. 3/29/2005 5:05 AM Hendrik
I had problems in my C# project with this code but I added a few lines and now it works perfectly

just add this in your code-behind

string id; // I need my ID when I select a checkBox
CheckBox ck1 = (CheckBox)sender;
DataGridItem dgItem = (DataGridItem)ck1.NamingContainer;

id = ((Label)dgItem.FindControl("lblID")).Text;//don't forget to add in your datagrid a Container lblID...

Response.Write ("You selected row " + id);

# re: How to use a checkbox in a datagrid template column. 3/30/2005 10:52 AM Scott
Hendrik, alternatively, you could have defined a datakey in you grid and used that :)

# re: How to use a checkbox in a datagrid template column. 4/2/2005 1:20 PM Vikram
You are an angel! Thank you god.

# re: How to use a checkbox in a datagrid template column. 4/6/2005 9:24 AM Stu
Great example, still no one has answered how to save check box state while navigating through the pages of the dataGrid. Any suggestions?

# re: Check box with grid haveing pagenation 4/7/2005 6:40 AM Coder
Hi,
Traping events and other functionality is great!!. But can you suggest a way how i can persiste the check box state across pages. ie when i select 3 check box and go to the second page and revisit the first page the check box loses it's state.
How do i solve this problem.

URGENT HELP REQUIRED!!!!!

# re: How to use a checkbox in a datagrid template column. 4/7/2005 7:57 AM Suresh
hi scott

I came across the thread thru google
http://www.geekswithblogs.net/sgreenberger/archive/2004/11/12/14871.aspx
and it had the solution to the problem of check box realting to the datagrid
i was able to solve my problem to some extent ..like to tigger the event
when i click the check box in the datagrid..
but....
i am not able get the value of the cell in the datagird....my code looks like


Public 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)
Dim val As String = dgItem.Cells(3).Text
Response.Write("The value You selected from the grid is " + val)

and the output i get is ..

The value You selected from the grid is

this is what i get..i think it display a null value...?

help me out..
Thank in advance



# re: How to use a checkbox in a datagrid template column. 4/7/2005 8:55 AM El Suprimo ASP.NET Developer
Hi Scott.
Can you tell me how I can display a bitmap image inside the actual checkbox, change the color through a transition effect when the checkbox state changes, and make the image automatically dim or brighten according to the lunar cycles?

I need this urgently!!! Please help!!!! I'm dying here!!!!

THANK YOU!!!!
Super-senior ASP.NET Developer


# re: How to use a checkbox in a datagrid template column. 4/11/2005 3:18 PM Scott
Super Senior Developer,
See my posting regarding your latest comment..Hope it helps :)

http://www.geekswithblogs.net/sgreenberger/archive/2005/04/11/30755.aspx

# re: How to use a checkbox in a datagrid template column. 4/12/2005 12:29 AM Raj
Great!!!!!!!! Helped a lot........
Thanks

# re: How to use a checkbox in a datagrid template column. 4/12/2005 4:11 AM Hennie
Hi Scott

Is there a way to get the DataKey field of the row in which the checkbox was checked?
What would the code look like? My Datakey field type is a sql server 2000 uniqueidentifier.

Thanks

# re: How to use a checkbox in a datagrid template column. 4/13/2005 12:28 AM Sumit sharma
This is a very good information

# re: How to use a checkbox in a datagrid template column. 4/14/2005 4:49 AM Sam
dont know whether this is possible, but what I want to do is using similar code to the above set the state of hidden columns on a row to visible when the checkbox is clicked, I would prefer if I didnt have to postback, but guess thats inevitable, anyway help anyone?

# re: How to use a checkbox in a datagrid template column. 4/14/2005 5:14 AM Adeel

in my code the chkpcc.checked=true is showing false, though it is checked.


Private Sub btngen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btngen.Click
Dim dgi As DataGridItem
Dim StrpccID As String
For Each dgi In dgCTrack.Items
Dim chkPCC As CheckBox
chkPCC = CType(dgi.FindControl("cbtPCC"), CheckBox)

If chkPCC.Checked = True Then
StrpccID += CType(dgi.Cells(1).FindControl("lblpccid"), Label).Text & ","
End If
Next
StrpccID = StrpccID.TrimEnd(",")
Session("PCCList") = StrpccID
Response.Redirect("newsaragencydetail.aspx")
End Sub

# re: How to use a checkbox in a datagrid template column. 4/15/2005 12:00 PM Airon
This was a big help! Thanks for sharing.

# re: How to use a checkbox in a datagrid template column. 4/15/2005 4:53 PM Scott
Adeel,
You've probably made the common mistake of not putting your databind in an if not IsPostback block.

# re: How to use a checkbox in a datagrid template column. 4/17/2005 8:35 AM Mary
i want to use the check box but also with the paging in the datagrid is their any solution?? tell me please

# re: How to use a checkbox in a datagrid template column. 4/19/2005 12:00 PM Vimla Gill
Scott-
This is very helpful. I think once in a while most of the programmer need this kind of solution for projects.


# re: How to use a checkbox in a datagrid template column. 4/20/2005 2:54 PM Natalie Gurevich
Thanks. You saved me a lot of time and nerves.

# re: How to use a checkbox in a datagrid template column. 4/29/2005 5:33 PM Hema
hi all, this is working......good.

CheckBox chkBox;
DataGridItem gridItem = null;
chkBox = (CheckBox)sender;
if(chkBox.Checked == true)
{
gridItem = (DataGridItem)chkBox.NamingContainer;
Label1.Text = gridItem.Cells[1].Text;
}


thanks

# re: How to use a checkbox in a datagrid template column. 5/3/2005 8:47 AM Cobrah
I have the same problem as Mary, the checkbox doesn't work with paging, it's only working on the first page of the datagrid

# re: How to use a checkbox in a datagrid template column. 5/11/2005 6:18 AM Nat
Thanks for this post, has helped me a lot. I have a datagrid which requires the checkbox.oncheckedchanged event to change the status of a textbox.ReadOnly to True.
Your code was clear and precise and allowed this to be done quickly.

Much Appreciated,
Nat

# re: How to use a checkbox in a datagrid template column. 5/11/2005 10:59 AM Steve
Thanks much. The post was very helpful with the project I'm working on.

# For those getting NULL 5/12/2005 5:13 AM Focalstream
For those of you always getting NULL, make sure the column is a bound column and not a template column. I was getting NULL when I evaluate dgItem.Cells[0].Text because column 0 happened to be a template column.

For those that have a multi-column key you might want to add your key columns as data bound columns and then set visible=false. This way you can capture your unique ids and submit your update.

Here is a sample in c#:
protected void cbSubscribe_Clicked(object sender, System.EventArgs e)
{
CheckBox ck1 = (CheckBox) sender;
DataGridItem dgItem = (DataGridItem) ck1.NamingContainer;

if ( ck1.Checked )
{
//update the database.
}
Label3.Text = "You selected row " + dgItem.ItemIndex.ToString() + " SurveyID: " + dgItem.Cells[0].Text + " TimeID: " + dgItem.Cells[1].Text;

}

Cheers!
steve

# re: How to use a checkbox in a datagrid template column. 6/7/2005 4:33 PM Jimmy
Very nice and easy solution, thanks!!

# re: How to use a checkbox in a datagrid template column. 6/8/2005 5:29 PM Justin
I am new to this but my Check_Clicked event will not fire

the code in the aspx is as follows:
<asp:TemplateColumn HeaderText="View">
<ItemTemplate>
<asp:CheckBox id="CheckBox1" AutoPostBack="true" Runat="server" OnCheckedChanged="Check_Clicked"></asp:CheckBox>


</ItemTemplate>
</asp:TemplateColumn>

my page load looks like this
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here

Dim strMEME As Long
strMEME = Request("strMEME")
If Not IsPostBack Then
Call Load_Members(strMEME)
End If


End Sub
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
any ideas why check_clicked won't fire?

# re: How to use a checkbox in a datagrid template column. 6/9/2005 3:11 AM Jayne
how would i go about selecting a checkbox that i have added in code as a template column in C#?i will really appreciate any help

jkoross@telkom.co.ke

# re: How to use a checkbox in a datagrid template column. 6/9/2005 3:27 AM jayne
Am creating a web page and i want to perform actions such as delete,update..depending on the checkbox status

jkoross@telkom.co.ke

# re: How to use a checkbox in a datagrid template column. 6/9/2005 2:11 PM Enrico
6 mitico! Questo è l'unico codice che funziona sul serio!!!

Very good! This code is very well!

# re: How to use a checkbox in a datagrid template column. 6/16/2005 7:59 PM Mona
Perfect! Thanks!

# re: How to use a checkbox in a datagrid template column. 6/22/2005 4:20 PM JamesT
Thank you SOOOO much for the assist.

# re: How to use a checkbox in a datagrid template column. 6/24/2005 8:52 PM keefah
Yeeha! Wow, this was EXACTLY what I was looking for. I just had to convert it to C# (thanks to those who posted some code). Many many thanks. -Nick


# re: How to use a checkbox in a datagrid template column. 6/25/2005 5:59 AM Simran Sharma
Great Code!!! But what if i want to allow the user to check a number of rows and instead of using AutoPostBack="True", make the user click a button and then make use of some values of the Checked Rows on click of the button.

# re: How to use a checkbox in a datagrid template column. 6/30/2005 10:54 AM Ben Hoxie
Hi. If you don't want to use autopostback and instead want to get all the values of a bound column at the end, when the user submits the form try something like this:

private void btnSubmit_Click(object sender, System.EventArgs e)
{
ArrayList selectedIDs = new ArrayList();

CheckBox cb;
foreach(System.Web.UI.WebControls.DataGridItem dgi in dgMyDG.Items)
{
cb= (CheckBox)dgi.FindControl("required");
if(cb.Checked)
selectedStepIDs.Add(dgi.Cells[1].Text);
}

//now our selectedID's is full of id's of checked ones!
}

# re: How to use a checkbox in a datagrid template column. 6/30/2005 10:56 AM Ben Hoxie
For clarification, in the last post the bound column with the item's ID is the second column (Cells[1]) and the name of the asp checkbox is "required". The datagrid dgMyDG is a protected class variable loaded in pageload.

# re: How to use a checkbox in a datagrid template column. 7/4/2005 10:59 PM Habib
Yes it works perfectly

Sub DoCommentCheck(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!
dim fChecked as boolean = ck1.Checked
Response.Write("You selected row " & dgItem.Cells(0).Text & " - " & fChecked)

End Sub

# re: How to use a checkbox in a datagrid template column. 7/5/2005 3:36 PM Annie
This is all great information. My question is how do i precheck a check box for the page.

This is what I have for my aspx page.
<input type="checkbox" name="selReason" id = "sel" checked =false runat="server" value ='<%# DataBinder.Eval(Container.DataItem,"ReasonCode") %>' >



# SAME FOR TEMPLATE IMAGE BUTTON 7/14/2005 2:09 PM TERRY
'-----------------------------------------------------
'IMAGE BUTTON CLICKED ON DATAGRID - OPEN FILE IN NEW WINDOW
Public Sub FileViewClicked(ByVal sender As Object, _
ByVal e As System.Web.UI.ImageClickEventArgs)
Dim btn As ImageButton = CType(sender, ImageButton)
Dim dgItem As DataGridItem = CType(btn.NamingContainer, DataGridItem)
'now we've got what we need!
'SET FULL_PATH SO THE NEXT FORM KNOWS WHAT TO SHOW
objRun.FILE_FULL_PATH = dgItem.Cells(4).Text
Response.Write("<script>window.open('frmFILE_SHOW.aspx','mywindow','width=400,height=550,toolbar=no,location=yes,directories=yes,status=no,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes, top=50, left=200')</script>")
End Sub

# re: How to use a checkbox in a datagrid template column. 7/18/2005 7:10 AM LIv
Cheers Scott. Your solution is great. Thanks heaps. Liv

# re: How to use a checkbox in a datagrid template column. 7/18/2005 7:19 AM Liv
Just in case anyone else was having the same problem I was I will post my specific implementation.

I didnt actually want to access the text of a cell since the value I needed, AccountHolderID, was not being displayed but was stored in the DataKeys collection and was assigned using the DataKeyField attribute of the DataGrid.

Then to access the AccountHolderID of the person selected in that row I used (c#)

DataGrid1.DataKeys[dgItem.ItemIndex].ToString()

This uses the index of the selected DataGridItem to retrieve the respective DataKey.

Hope this is helpful for someone.

# re: How to use a checkbox in a datagrid template column. 7/20/2005 6:44 AM sony
thousand times thanks to you all

# re: How to use a checkbox in a datagrid template column. 7/20/2005 6:57 AM vinay
Hi all,
To add a checkbox in a grid just make a template column. Then go to design mode and right click on grid, select edit template item add in item template add a checkbox. Then after adding right click and end template editing.

# re: How to use a checkbox in a datagrid template column. 8/2/2005 6:26 PM Mike Nichols
Here's how I solved creating checkbox columns dynamically while retaining state and so on...if you add controls in the load event, be sure you add the grid to the control tree prior to binding and don't bind on postback unless the datasource changed....:

I had cached DataSet which I wanted to use to build a grid dynamically each time the user selected from a dropdownlist, which corresponded to each table in the DataSet. I created a CheckBoxColumn which derived from ITemplate and added a custom event that was fired from the CheckBox's "CheckedChanged" event which is built in. Within this event, I'd query the checkbox's NamingContainer, which is the DataGridItem containing the checkbox. So now I've got my row reference. I created a custom DataGridCoordinateEventArgs class that holds the ColumnName and DataGridItem.ItemIndex I had just extracted and this gets passed as the event args into my custom event that is fired from the CheckedChanged event. This in turn gets captured on the PostBack to the form where I can extract the DataGridCoordinateEventArgs ColumnName and ItemIndex and perform some action on it in the wired up eventhandler. I was even able to do this in a completely dynamic datagrid...the only caveat is the AutoPostBack attribute should be true for the checkboxes in the column. If there isn't a lot of processing during rendering, this is minor. Best part, it is entirely event driven and sounds really cool :)
Hope this helps.

# re: How to use a checkbox in a datagrid template column. 8/11/2005 3:21 AM Jeff Yates
hi Guys,

Thanks for this. The Autopostback=true solved the problem for my dynamically created Template Checkboxes. That was quite of tough one.

Cheers!


# re: How to use a checkbox in a datagrid template column. 8/22/2005 11:31 AM ernest
i too was having trouble not getting the checkbox to fire off, but after i read Darren's post i got it to work. i was doing a databind on page_load which actually reset the checkbox. by moving my databind within the If Not Page.IsPostBack evaluation caused the checkbox to work. thanks for the tips!

# re: How to use a checkbox in a datagrid template column. 8/23/2005 9:15 AM Candace Sweigart
Hi Scott,

Thank you for the great article! It has really helped. I have just one question. My checkchanged event fires when I check the checkbox, but not when I uncheck it. Do you know what the problem could be related to?

Regards,
Candace


# re: How to use a checkbox in a datagrid template column. 8/31/2005 11:28 AM Justin
Great information - thanks Scott!

# re: How to use a checkbox in a datagrid template column. 9/1/2005 2:11 PM TroyHusker
UREKA!! This is PERFECT!! Thanks!

I needed to be able to toggle a couple of DIV on and off based on the status of the check box.

Here's the code I used:

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

Dim cb As CheckBox = CType(sender, CheckBox)
Dim dgItem As DataGridItem = CType(cb.NamingContainer, DataGridItem)
Dim divB As HtmlGenericControl
Dim divP As HtmlGenericControl
divB = CType(dgItem.FindControl("divBusiness"), HtmlGenericControl)
divP = CType(dgItem.FindControl("divPerson"), HtmlGenericControl)
If cb.Checked Then
divB.Style("display") = "block"
divP.Style("display") = "none"
Else
divB.Style("display") = "none"
divP.Style("display") = "block"
End If
End Sub

# re: How to use a checkbox in a datagrid template column. 9/8/2005 12:39 PM nLella
Thanks a lot; I have implemented it in C# with a little modification to maintain the chackbox state with custom paging in a DataGrid and it works like a charm.
Thanks again

# re: How to use a checkbox in a datagrid template column. 9/19/2005 8:33 PM K.Senthil Kumar (Sensoft2000)
Finally, i got solution.. thankx.. But can we do without postback, and with the ceodebehind? i am waiting here....

# re: How to use a checkbox in a datagrid template column. 9/26/2005 2:48 AM Loren
hi, I just want ot THANK YOU so much for the help. The code is clean and easy! I had some problems getting my checkbox's oncheckchanged method to call my sub, but then I got it to work just by putting an if not postback in my page load! So thank you very much for this.... It helped me loads!!!!

# re: How to use a checkbox in a datagrid template column. 10/4/2005 2:24 AM Shameem
Thank you. Great work and is very useful to my project

# re: How to use a checkbox in a datagrid template column. 10/5/2005 7:02 AM junior developer
Hi Guys,

I have had a quick look at this and it seems like what i need to do. I have a datagrid that incorporates checkboxes through an item template. I need to record the info about the checked and unchecked rows into two diff collections respectively once an update button is hit! Can anyone offer some help (soing this in C#)? Thanks in advance

# re: How to use a checkbox in a datagrid template column. 10/20/2005 11:04 PM Ganesh
Thanks for your most important note as i was facing problem in checkbox.
Check_Changed event was not firing but from yr reply i can now do it by keeping auto post back property to true.
Thnkssssssssssssssss Nimesh & Alpesh

# re: How to use a checkbox in a datagrid template column. 11/2/2005 11:42 AM .NET.Chicago
Scott,

Looks good, I already knew that but here is a little trick question (which I have been trying to figure out): as you move from a page to a page, in a paginated datagrid, you need to rebind the data to the grid -- well, everyone knows that. Well, the problem is that the checked state of a checkbox, after rebinding the data, will not be there. Okay, here is an example: I check records 1,2,5,10 on page 1 of a paginated datagrid, then move to page 2 and do some stuff, then go back to page 1, and all the checkboxes I previously checked are unchecked now, due to data rebinding to the grid. Any ideas how to keep the checked state alive as you move from page to page?

Thanks

SC

# re: How to use a checkbox in a datagrid template column. 11/7/2005 3:22 PM yami
Scott,
I have a checkbox placed inside a datagrid and this datagrid ia placed inside another Master DataGrid, Now my question is, when the checkbox in the child datagrid is checked I want my textbox in the Master DataGrid to be enabled or disabled.Any idea how to proceed with this.

# re: How to use a checkbox in a datagrid template column. 11/11/2005 2:47 PM Harun
Hi scott,
is there any way to maintain state of checkboxes in a paginated datagrid? is there a road map to implement.?

# re: How to use a checkbox in a datagrid template column. 12/14/2005 9:14 AM Dan
Scott,
Thanks for your helpful posting!

# re: How to use a checkbox in a datagrid template column. 12/22/2005 12:03 AM Laurent Bourgeois
This is very usefull. I am using it in c#. First I was surprised there wasn't any event binding code like "checkbox1.checkedchange += ...". I supposed this is done internally thanks to the ASP.NET plumbing.
Thank you very much for discovering that miracle.

# re: How to use a checkbox in a datagrid template column. 12/26/2005 3:15 AM santhi
I have a checkbox in the header of the datagrid.If i click the check box all the items should be selected.How can this be done.

# re: How to use a checkbox in a datagrid template column. 12/29/2005 1:56 AM Yogesh
Great work.....

It helped me lot...

This short snippet deserves strong appretiations

Regards,
Yogesh

# re: How to use a checkbox in a datagrid template column. 1/11/2006 10:42 AM Vicky
hi,Its realy a good code that is workin really good in my applications

# re: How to use a checkbox in a datagrid template column. 1/24/2006 1:11 PM Edgars
Excelet solution! This thread really helped me.
If you will use Infragistics, then

Dim btnInCell As ImageButton = CType(sender, ImageButton)
Dim dgItem As Infragistics.WebUI.UltraWebGrid.CellItem = CType(btnInCell.NamingContainer, Infragistics.WebUI.UltraWebGrid.CellItem)
Dim RowPrimaryKey As Integer = dgItem.Cell.Row.Cells(0).Value()


# How to use a checkbox in a datagrid template column. 2/3/2006 3:29 AM swati
how to select all the checkboxes in the template column on the click of a checkbox present in the header template of template column

# re: How to use a checkbox in a datagrid template column. 2/8/2006 6:03 AM Jebarson
Well none here is there to provide the solution for client side access. here it is take it.



//--------------------------------------------------------------------------------------------
//this is to select or unselect the datagrid check boxes


function DGSelectOrUnselectAll(grdid,obj,objlist){

if(obj.checked)
DGSelectAll(grdid,objlist)
else
DGUnselectAll(grdid,objlist)
}
//----------
function DGSelectAll(grdid,objid){
var chkbox;
var i=2;

chkbox=document.getElementById(grdid + '__ctl' + i + '_' + objid);

while(chkbox!=null){
chkbox.checked=true;
i=i+1;
chkbox=document.getElementById(grdid + '__ctl' + i + '_' + objid);
}
}
//--------------
function DGUnselectAll(grdid,objid){
var chkbox;
var i=2;

chkbox=document.getElementById(grdid + '__ctl' + i + '_' + objid);

while(chkbox!=null){
chkbox.checked=false;
i=i+1;
chkbox=document.getElementById(grdid + '__ctl' + i + '_' + objid);
}
}

//--------------------------------------------------------------------------



<asp:TemplateColumn>
<HeaderTemplate>
<Input id="checkAll" type=checkbox onclick="DGSelectOrUnselectAll('DataGrid1',this,'chkDel')" >
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkDel" Runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>


# re: How to use a checkbox in a datagrid template column. 2/9/2006 9:13 PM AselaW
Hi,
I need to add a Checkbox to a Header! The Only problem being that I cant do it at Runtime and all the Bands and Columns have been desinged at the back end. I have to add a checkbox to select/unselect all to Band[2].Column[7] Please help me out coz I have to release my code by evening! Thanks Guys!

# Check Boxes in Datagrid should display wherever I want in the columns 2/14/2006 11:20 PM kireeti
I have a requirement. I want to display check boxes to the groups like (Group A, Group B..etc). Under each group I want to display the subject Names with no check boxes. Please help any one knows the logic or code.

# re: How to add a checkbox in a datagrid template column. 2/16/2006 9:06 PM deepak
i need to add a checkbox for a particular cell

# re: How to use a checkbox in a datagrid template column. 2/20/2006 7:48 PM densha otoko
anyone wants to post a code that works across pages? i badly need it.

# re: How to use a checkbox in a datagrid template column. 2/23/2006 11:26 AM Amar
the databinding in postback info is very useful thx for solving my problem!

# re: How to use a checkbox in a datagrid template column. 2/24/2006 8:17 AM VS
Thank you, It works great. It took just a minute get my code working.

# re: How to use a checkbox in a datagrid template column. 3/14/2006 2:21 AM Rajesh
Thank you .Your code helped me much

# re: How to use a checkbox in a datagrid template column. 3/14/2006 2:40 AM Revathy
Thank You very much. My need was to do some operation on only the rows that were checked , when the user submits the form. I just had to convert it into vb. So I am providing the vb code below .It might be helping to someone.

dim cb as new CheckBox
dim selectedIDs as new ArrayList
rowcount - the no: of rows of the datagrid

For i = 0 To rowcount - 1
cb = CType(DatagridName.Items(i).FindControl("CheckBox1"), CheckBox)
If cb.Checked Then
selectedIDs.Add(DatagridName.Items(i).Cells(index).Text)
End If
Next
For i = 0 To selectedIDs.Count - 1
//code to be applied on the checked rows
Next


# re: How to use a checkbox in a datagrid template column. 3/14/2006 5:32 PM KB
Is there a way to do this in windows forms?

# re: How to use a checkbox in a datagrid template column. 3/15/2006 9:23 AM Andrew C
Thanks this article helped me a great deal

# re: How to use a checkbox in a datagrid template column. 3/15/2006 12:34 PM Andrew C
'** Here is some code that I created from the above snippets to highlight/un-highlight a row of data **'

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)

SetBackgroundColor(dgItem.DataSetIndex, ck1.Checked)
End Sub

Private Sub SetBackgroundColor(ByVal piSelectedIndex As Integer, ByVal pbChecked As Boolean)
Dim piIndex As Integer

Dim mlNotSelectedBackColor As System.Drawing.Color = mlNotSelectedBackColor.White
Dim mlSelectedBackColor As System.Drawing.Color = mlSelectedBackColor.Gainsboro

With datSearchResults
For piIndex = 0 To .Items(1).Cells.Count - 1 Step 1
If pbChecked Then
'** Set to gray if selected **'
.Items(piSelectedIndex).Cells(piIndex).BackColor = mlNotSelectedBackColor.Gainsboro
Else
'** Set to white if unselected **'
.Items(piSelectedIndex).Cells(piIndex).BackColor = mlNotSelectedBackColor.White
End If
Next
End With
End Sub

# re: How to use a checkbox in a datagrid template column. 3/15/2006 1:41 PM JD
It works great for 'check' but what if the user checks and then unchecks? how do we trap that?

thanx,
JD

# re: How to use a checkbox in a datagrid template column. 3/18/2006 1:17 AM Manish
*****code******
Public Sub Check_Clicked(ByVal sender As Object, ByVal e As EventArgs)
Dim strSQL As String
Dim strItemNo As String
On Error GoTo Check_Clicked_Err
Dim ck1 As CheckBox = CType(sender, CheckBox)
Dim dgItem As DataGridItem = CType(ck1.NamingContainer, DataGridItem)
Dim ProductID As Integer
Dim intItem As String = dgItem.ItemIndex 'this line gets the index of the row
ProductID = dgProducts.DataKeys.Item (intItem) 'this line gets the datakey of the indexed row
If sender.checked Then
strSQL = "UPDATE tblProducts SET Inactive = 1 WHERE ProductID = " & ProductID
Else
strSQL = "UPDATE tblProducts SET Inactive = 0 WHERE ProductID = " & ProductID
End If
ExecuteSQLStatement(strSQL)

Check_Clicked_Exit:
Exit Sub

Check_Clicked_Err:
Session("Error") = "An error occurred updating this product!"
GoTo Check_Clicked_Exit

End Sub
*****end*******



# re: How to use a checkbox in a datagrid template column. 4/11/2006 2:50 AM Balaji
I have 6 template column in a datagrid to accept the Quantity, Price etc, Problem is if add so data to the first page and go to fill the data in second page and come back to the first page my data is cleared in first page. How to handle this situation.

Regd
Balaji

# re: How to use a checkbox in a datagrid template column. 4/20/2006 3:23 AM Martin
Here is a link to an article about preserving checkbox state across pages:
http://www.codeproject.com/aspnet/CheckStatePersisting.asp

# re: How to use a checkbox in a datagrid template column. 5/9/2006 3:36 PM Greg
I got it to work to the point of firing the Click event.
In order to prepopulate the checkboxes I have;
public void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox check = (CheckBox)e.Row.FindControl("chkSelect");
if (check != null & e.Row.DataItem != null)
{
check.Checked = Convert.ToBoolean(((SSI.ColumnsForReport)(e.Row.DataItem)).Include_in_Report);
}
}
}

The problem that causes is that when I get to this line of code;
DataGridItem dgItem = (DataGridItem)ck1.NamingContainer;

an error is thrown;
Unable to cast object of type 'System.Web.UI.WebControls.GridViewRow' to type 'System.Web.UI.WebControls.DataGridItem'."}

# re: How to use a checkbox in a datagrid template column. 5/9/2006 4:10 PM Greg Hazzard
That was easy to fix.

GridViewRow gvRow = (GridViewRow)ck1.NamingContainer;
string value = gvRow.Cells[0].Text;
string value1 = gvRow.Cells[1].Text;

# re: How to use a checkbox in a datagrid template column. 5/11/2006 10:54 PM sarika
i have used all the code given by u bt code did't work.plz help me hw a row is selected on check change in a datagrid

# re: How to use a checkbox in a datagrid template column. 5/12/2006 3:00 AM sonu
can anybody help me?I hav to select the row in datagrid onclick the checkbox and it will change the color of that row on selection. i hae used the following code-
private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item)
{
//e.Item.Attributes.Add("onmouseover","this.style.backgroundColor='beige'");

e.Item.Attributes.Add("onclick","javascript:window.location" + e.Item.Cells[0].backcolour + "'");
}
if(e.Item.ItemType == ListItemType.AlternatingItem)
{
//e.Item.Attributes.Add("onmouseover","this.style.backgroundColor='beige'");

e.Item.Attributes.Add("onclick","javascript:window.location" + e.Item.Cells[0].backcolor + "'");
}

}
this code will change the color on selection bt on uncheked it didn't work,
plz send me suggestion

# re: How to use a checkbox in a Flexgrid template column. 5/30/2006 12:22 AM Vipul Shah
I am Student

# re: How to use a checkbox in a datagrid template column. 5/30/2006 11:42 AM Leigh Anne
Ok, I'm having major trouble with this. I have a Data Grid and a template column filled with checkboxes. I added the "Check_Clicked" sub and OnCheckedChanged="Check_Clicked" in the code behind. However, I'm an extremely green beginner. I don't know what to bind the data to. I am returning a grid with a bunch of college courses. The last column in the grid is a checkbox for "Drop." My goal is for the student to put a check in the "Drop" box for any course they're dropping, then hit a Submit button. The Submit button will fire an email to the student's advisor. I can't figure out how to get the info from the grid based on the checkbox. Sorry if this doesn't make sense. I have no experience other than finishing the Wrox Beginning ASP.NET 2.0 book.

# re: How to use a checkbox in a datagrid template column. 6/12/2006 10:49 PM Gaurav Tiwari
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox id="my_chkbox" runat="server" AutoPostBack="True" OnCheckedChanged="check" Text="CHK_BOX">
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>


public void check(object sender, System.EventArgs e)
{
CheckBox chkTemp = (CheckBox)sender;
DataGridItem dgi = (DataGridItem) chkTemp.NamingContainer;

if(chkTemp.Checked)
{
Response.Write("Check Found");
}

}


still the event does not fire ...

please send response to gauravtiwari8778@yahoo.com

# re: How to use a checkbox in a datagrid template column. 6/18/2006 10:07 PM Rob
Darren,
Thanks for posting your error as I was doing the exact same thing. I kept seening the page re-load, but I think I was to tired to figure out what that meant.

#  How to use a checkbox in a datagrid template column. 6/20/2006 10:32 PM kiran
hi all,
i saw all above query its fine..
can you send me How to use a checkbox in a datagrid template column., main purpose is to when i click on check box, i want one column value of that paticular row.. so please send me the code..

mail: kiran.kt29@gmail.com
kiranttt@yahoo.co.in

# re: How to use a checkbox in a datagrid template column. 6/28/2006 10:45 AM sukarthi
Hi Scott,
This code was very helpfull and used in my code and it works great!!!. Nice Job. :-)

# re: How to use a checkbox in a datagrid template column. 7/2/2006 9:48 PM subrahmanyam
Every thing is fine. But I'm looking for a solution to catch the chekc box clicked (state) event with out giving autopostback =true

can anybody help me how to check the state of a check box with out setting autopost back =true


# re: How to use a checkbox in a datagrid template column. 7/10/2006 11:28 PM Dayananthan
Thanks Scott !! Its working Fine...

# re: How to use a checkbox in a datagrid template column. 7/13/2006 12:35 AM Eeshu
I have written the same code as said above. But I think the event is not firing. When I am checking the checkbox, I am not able to get the value of the item checked in the label I have assigned. Any help is welcomed.
Thanks in advance.
U could send replies to sireesha_naidu@satyam.com



# re: How to use a checkbox in a datagrid template column. 7/13/2006 11:45 PM Eeshu
scott, I could not retrieve the value into the label .
It is refering to a null value. by using your procedure

# re: How to use a checkbox in a datagrid template column. 7/15/2006 12:57 AM Eeshu
Thanks Steve, It helped me great. I was always getting null value. Now, I got my problem solved.

Thanks thanks thanks

# re: How to use a checkbox in a datagrid template column. 7/18/2006 9:16 AM dotnet geek
just wat i was looking for .... capture chkbox click on dg ... nicely done
cheers \~_~/

# re: How to use a checkbox in a datagrid template column. 8/4/2006 3:26 AM Buntee
The code didn't work when I am un checking the box. The even is not triggered. Can you let me know like how to proceed from here

# re: How to use a checkbox in a datagrid template column. 8/9/2006 5:18 AM Kaushik
Hi,

I tried and the code worked fine. If you want to display the value of a another column based on that checked column in that particular row just follow the below line of code :

CheckBox c1=((CheckBox)sender);
DataGridItem dgi=(DataGridItem)c1.NamingContainer;
Label1.Text=((Label)dgi.FindControl("lbl1")).Text;

It is valid for any type of control you are using.
But you must cast to the appropriate type.

Now the other problem is the checkedchanged event is not firing when the checked property is changed to false.

Can anybody suggest how to make it happen.

mailid : kaushik93@yahoo.com

Thanks,
Kaushik.

# re: How to use a checkbox in a datagrid template column. 8/11/2006 12:43 PM BillR
I have the same problem that another post states.(from "Olivia")
I've got a checkbox in a DataGrid. When I check it, the event fires. When I uncheck it, no event fires.

Any suggestions would be gratefully appreciated.

Thanks

Bill

# re: How to use a checkbox in a datagrid template column. 8/11/2006 12:54 PM BillR
I meant to add my email address to the last post (re: event not firing if checkbox UNCHECKED)
If you want to ping me directly, you can do so at wryan@verdasys.com
MANY THANKS!

# re: How to use a checkbox in a datagrid template column. 8/22/2006 8:17 PM misuri
how to update checkbox in datagrid from select statement in database

# re: How to use a checkbox in a datagrid template column. 9/12/2006 10:51 AM sami
How to Get the Value from different pages when checkbox is selected on datagrid.

# re: How to use a checkbox in a datagrid template column. 9/26/2006 4:03 PM MarliseS
What am I doing wrong if my OnCheckedChanged event never triggers? This is in the datagrid:
<asp:TemplateColumn HeaderText="Fina- lise">
<ItemTemplate>
<asp:CheckBox AutoPostBack="true" OnCheckedChanged="chkFinalise_Clicked" ID="chkFinalise" Width="15" Runat="server" Checked=<%# DataBinder.Eval(Container.DataItem, "Finalise") %>></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>

And the code:

public void chkFinalise_Clicked(object sender, EventArgs e)
{
...
}

# re: How to use a checkbox in a datagrid template column. 10/4/2006 5:51 AM cohenc
Having the same problem : event not firing on the UNCHECK, but firing on checkn and I want to get back the state of the checkbox I've just clicked. If anyone has an idea, my mail is : raphael.cohen@gmail.com

# re: How to use a checkbox in a datagrid template column. 10/23/2006 10:00 AM Kamal H
I have used the code, but it would not fire Check_click procedure.
What could go wrong here?

thanks

# How to add a checkbox in the column header of a datagrid 11/8/2006 3:25 AM Aravind
i need to add a checkbox in the column header of a datagrid...plz help me with a c# code..

# re: How to use a checkbox in a datagrid template column. 11/29/2006 6:27 AM Pooja
Hi Scott,
This code was really very helpfull and used in my code and it works great!!!.

# re: How to use a checkbox in a datagrid template column. 12/5/2006 1:40 PM Enreil
Thank you for the valuable solution. I was facing exactly the same problem, and I'm grateful you helped me solve it quickly. I'd give you points if I could.

# re: How to use a checkbox in a datagrid template column. 12/8/2006 1:53 AM Sachin
Hi Scott, Really a gr8 code,it helped me very much...
Thankx a lot

# re: How to use a checkbox in a datagrid template column. 12/14/2006 12:06 AM Suresh V
Hi,
I've a varied question. I've a datagrid with checkboxes and a linkbutton outside the grid.The functionality is select all items via checkbox in the datagrid header and click the outside linkbutton to fire a postback and build selected item list based on one of the column in the selected row and perform some actions. Checkbox is working fine but I'm not able to retrieve a ItemTemplate Column (LinkButton) value on postback when fired from the outside linkbutton. Any idea?

# how to display the checked values of the check box on a page on click of submit button 12/19/2006 8:33 AM som
I want to display the selected items of the check box on click of submit button.......plz help

# re: How to use a checkbox in a datagrid template column. 1/16/2007 12:20 AM Priya
Hi,
I need C# euivalent for these staments:
Dim ck1 As CheckBox = CType(sender, CheckBox)
Dim dgItem As DataGridItem = CType(ck1.NamingContainer, DataGridItem)


# re: How to use a checkbox in a datagrid template column. 1/30/2007 2:12 AM Billy
Ok with ASP CHeckbox
What if in the template column we had a html checkbox

<input name="name" class="checkbox" type=type="checkbox">

how could we use this kind of checkbox?


# re: How to use a checkbox in a datagrid template column. 2/7/2007 8:06 AM Paulra
I want to count the number of rows checked in a datagrid (in a loop) and display a message. I dont want autopostback = "true" since I am not going to do any action at each check_click event. after all rows are selected a button will be clicked. to be more specific the user selects the rows to be deleted and i want to display a confiramtion message. Can any one help me with this in c#. I need help with getting the checked value and the confiramtion message box
thanks in advance

# re: How to use a checkbox in a datagrid template column. 2/16/2007 12:16 AM RajhaRajesuwari
if the checkbox event is not fired make the following change in the pageload event to bind the datagrid

if(! IsPostBack)
BindData();
it worked out for me

# re: How to use a checkbox in a datagrid template column. 2/21/2007 8:54 AM Sujith
i have a datagrid. i'm creating template columns (check boxes) (n number) dynamically..

(Just imagine - to mark attendance of a training program - which may be 1 day training, some time 5 day training... like that). So I am preparing datagrid dynamically...

that part is workin fine.




now., i am not able to get the value of these check boxes.. I tried Datagrid1.Item[i].Cell[j].FindControl method, which is not wrkin...

please...

# re: How to use a checkbox in a datagrid template column. 2/21/2007 8:56 AM Sujith
if any one know the solution for my above problem, pleaseeee mail to me.. very urgent sujith.chandran.nair@gmai.com

# re: How to use a checkbox in a datagrid template column. 3/8/2007 7:46 AM Questionare
I have inserted a Checkbox into the ItemTemplete and changed the ID, but I can not use this in coding Eg.(chkbox1.Checked = True) ?

# how to update a row in datagrid when checkbox is checked without using edititemtemplates 4/2/2007 5:40 AM swapna
i want to know how to add a new row to datagrid when a button is clicked

# re: How to use a checkbox in a datagrid template column. 5/31/2007 9:54 AM Mark
If your Event is firing OK but the Sub is not executing it may be because you need:

EnableViewState="True"

in your GridView e.g:

<asp:GridView ID="grvApl" runat="server" AutoGenerateColumns="False" EnableViewState="True" DataKeyNames="AplStdID" >

Mark

# re: How to use a checkbox in a datagrid template column. 6/25/2007 4:51 AM 9p90-9-9
























































































a






















# God job, dude! 6/27/2007 4:09 PM Suru
God job, dude, your post (the first on top) was the one I was looking for.

The only thing I have to do it's translate the code from VB to C#. Works fine on both languages.

Have a nice live, dude!


See you.

# re: How to use a checkbox in a datagrid template column. 7/23/2007 1:07 PM dinesh
how to update a row in datagrid when checkbox is checked without using edititemtemplates

# re: How to use a checkbox in a datagrid template column. 7/26/2007 2:57 PM pavi
Checkbox .checked property always returns false even though it is checked

# re: How to use a checkbox in a datagrid template column. 10/9/2007 4:52 AM Karen
hi RajhaRajesuwari,
if (!isPostBack) ....
It works for me. Thanks

# re: How to use a checkbox in a datagrid template column. 12/17/2007 3:50 PM Mandeep
I want To Bind the Datagrid On Click Of Button and On Checking and Unchecking the Checkboxes it Display the
Status Of CheckBox Whether Is Checked Or not. and Display the RowId Of that Row
I think This Code Will Not Work For that Purpose

# re: How to use a checkbox in a datagrid template column. 12/26/2007 3:21 AM pooja
foreach (DataGridItem di in MyDataGrid.Items)
{
CheckBox chkBx = (CheckBox)di.Cells[5].Controls[1];
//chkBx= (CheckBox)MyDataGrid.FindControl("CheckBox1");

if (chkBx != null && chkBx.Checked)
{
Response.Write("Checked." + "<br>");
Response.Write(chkBx.Checked.ToString());
}
else
Response.Write("Not checked." + "<br>");
Response.Write(chkBx.Checked.ToString());
}

im not getin d value if my checkbox is check or not im using asp.net2.0 n c#

# re: How to use a checkbox in a datagrid template column. 12/29/2007 4:08 AM Keyur
Its Few lines of code but solved my critical problem...Good Job..Thankz

# re: How to use a checkbox in a datagrid template column. 1/30/2008 10:41 PM geervani
really great. simple solution

# re: How to use a checkbox in a datagrid template column. 2/5/2008 5:49 AM MindGrill
Thanx for the same.
It is really very useful for me.

MindGrill
http://mindgrillQ.blogspot.com - Interview Questions Helpline

# re: How to use a checkbox in a datagrid template column. 3/28/2008 8:34 PM su deposu
how to update a row in datagrid when checkbox is checked without using editi temtemplates ...

# if i have a gridview with itemtemplate as checkbox i select one checkbox on one row of one page and i go to next page and i sele 5/30/2008 12:20 PM swaminatham
hi plz help me for the code using sessions in c#

# how to find the checkbox in header template when we click on item template checkbox using codebehiend. 6/24/2008 9:22 AM alankit
i want to do this without using javascript need an answer

# re: How to use a checkbox in a datagrid template column. 7/15/2008 2:06 AM Lanselot
Excelent piece of code

# re: How to use a checkbox in a datagrid template column. 7/16/2008 1:56 AM asp
Hi,
I use the oncheckedchanged event and it gets fired and all is well but I re-populate the grid immediately after. And the oncheckchenaged event gets fired again. Is there a way to stop this?

Thanks

# re: How to use a checkbox in a datagrid template column.it is problem 7/31/2008 8:54 AM karthi
{
dtStore =(DataTable)ViewState["dtStore"];

int iCurrent = Grid_FD_Store.CurrentPageIndex;
if (iCurrent > 0)
{
iCurrent = Grid_FD_Store.CurrentPageIndex * 15;
}
string fgf=Grid_FD_Store.Items.Count.ToString();;

for (int i=0;i<Grid_FD_Store.Items.Count;i++)
{
string sStoreStatus=dtStore.Rows[iCurrent+i]["All"].ToString();
if(sStoreStatus=="Y")
{
((CheckBox)Grid_FD_Store.Items[i].Cells[3].Controls[1]).Checked = true;
}
}
}

# re: How to use a checkbox in a datagrid template column. 8/12/2008 5:32 AM calvin briones
walang kwenta!!!!!!!!!!
wala d2 hinahanap ko!!!!!!!!!!!!



bweiset!!!!

# re: How to use a checkbox in a datagrid template column. 9/29/2008 5:19 AM abhilash
great work..thanks

# re: How to use a checkbox in a datagrid template column. 10/21/2008 4:51 AM yuva
the code didn't work: I got error "Unable to cast object of type 'System.Web.UI.WebControls.GridViewRow' to type 'System.Web.UI.WebControls.DataGridItem' from the line Dim dgItem As DataGridItem = CType(ck1.NamingContainer, DataGridItem).
Help me.........

# re: How to use a checkbox in a datagrid template column. 10/27/2008 4:36 AM arnold
hi,
iam using checkboxes in 2 columns(template col) in each row .On clicking a checkbox i want to check whether the other one in the corresponding row is checked.if so ,previously checked one should be unchecked(like in a radio button list)

i need ur help
very URGENT!!!pls help

# re: How to use a checkbox in a datagrid template column. 10/28/2008 5:22 AM ASP Senior Developer
Hey Scott You dont have an answer?

# re: How to use a checkbox in a datagrid template column. 10/29/2008 3:19 AM ASP Senior Developer
You bleedy scott

# re: How to use a checkbox in a datagrid template column. 11/12/2008 4:19 AM we
bla bla blah

# re: How to use a checkbox in a datagrid template column. 11/19/2008 12:05 AM Lavanya
actually i want to selcect one row in the datagrid by using the check box which is in item template. after selecting the row i want to move up and move down the row by clicking move up move down button .note this move up and move down buttons are in the form not inside the grid. can you help me

# re: How to use a checkbox in a datagrid template column. 11/27/2008 3:55 AM Dave

Very nice and effective, with that NamingContrainer.
Thank you!

# re: How to use a checkbox in a datagrid template column. 12/4/2008 3:21 PM Natalia
Hi
Have the next problem: I have the check box in a colum of the ultra web grid, I used it to update some information on sql, when the user cheks it uses the autopostback and checked_changed event to update the information, however when I chek the box, it calls the checked_changed event, updates the information and goes again in the same event (checked_changed) and updates the same information, the even is called twice for evey check event i do. Can some body help me :(

# re: How to use a checkbox in a datagrid template column. 12/18/2008 1:52 AM ASP Senior Developer
scott!!!
Are you dead?

# how to place checkbox in datagrid head field 12/30/2008 3:59 AM ravindra
if i select the header fileld checkbox .the all checkboxes has to be selected

# re: How to use a checkbox in a datagrid template column. 12/30/2008 7:26 AM webloji
Thank you


http://adf.webloji.net

# re: How to use a checkbox in a datagrid template column. 1/22/2009 8:56 AM UncleJonny
Great code! I wish I had read through some of the answers much sooner yesterday and I would have found that I was resetting my grid by not using the !IsPostBack condition. Must me nice to know that even after 4 years of originally posting this you're code is still helping us. Keep up the good work!

# re: How to use a checkbox in a datagrid template column. 1/22/2009 10:59 AM John Caballero
Here is what I came up with after reading through the responses.


void globalCheck(object sender, System.EventArgs ea)
{
try
{
System.Web.UI.WebControls.CheckBox chkBox;
chkBox = (CheckBox) sender;
DataGridItem dgItem = (DataGridItem)chkBox.NamingContainer;
bool chkd = chkBox.Checked;

foreach(DataGridItem i in ITEM_LIST.Items)
{
((CheckBox)i.FindControl("LINE_ITEM_CHECK")).Checked = chkd;
}

}
catch(Exception e)
{
Response.Write(e);
}
}


# re: How to use a checkbox in a datagrid template column. 3/25/2009 8:22 AM Willem vd Westhuizen
Thanks!!!!!!!


# re: How to use a checkbox in a datagrid template column. 3/31/2009 10:31 PM Tai Zhang
for guys who wanna C# code
==========================
protected void CheckBox_GridView_GoodReceived_Edit_CheckedChanged(object sender, EventArgs e)
{
CheckBox thisCheckBox = ((CheckBox)sender);

if (thisCheckBox.Checked)
{
((TextBox)(thisCheckBox.NamingContainer.FindControl("TextBox_GridView_GoodReceivedDate"))).Text = DateTime.Now.ToString("dd-MMM-yyyy");
}
else
{
((TextBox)(thisCheckBox.NamingContainer.FindControl("TextBox_GridView_GoodReceivedDate"))).Text = "";
}
}

# re: How to use a checkbox in a datagrid template column. 4/22/2009 9:30 PM Snow
Hi,can someone help me,i had problem with c# that i have no idea how to use boolean to grab the result with user checked with value,then capture as the rows will shown at another data grid.


Thanks in advance...

Post Feedback

Title:
Name:
Email: (never displayed)
Url:
Comments: