Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Binding Checkbox in GridView (A work around)

, 16 Sep 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
I needed to bind a checkbox in gridview to a database field but to my disappointment I found that this was not easy. We could bind “Text” property but what if I don’t want to display the value I am binding (e.g. ID of that record). Here is a work around. I added a hidden… Con

I needed to bind a checkbox in gridview to a database field but to my disappointment I found that this was not easy. We could bind “Text” property but what if I don’t want to display the value I am binding (e.g. ID of that record). Here is a work around.

I added a hidden field next to checkbox like below.

<span id=”spanTextBox”>
<asp:CheckBox ID=”chkItem” runat="”server”" Checked=”false” />
<asp:HiddenField ID=”hfdID” Value=” runat="”server”" />
</span>

It’s easy to access this from server side but if you want the value (intOrderId in my case) in javascript on checkbox click it requires a little trick.

I added a javascript function to each checkbox in databound event of grid.

protected void dgvOrders_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox chk = e.Row.FindControl(“chkItem”) as CheckBox;
chk.Attributes.Add(“onclick”, “CheckChanged(‘” + chk.ClientID + “‘);”);
}
}

Javascript function added above goes here.

function CheckChanged(id) {
// The line below returns the value of that hidden field we just added.
// So in my case I get the intOrderId value here.
// Note that both these controls should be in a separate container
// like it have added it in the span.
var text = document.getElementById(id).nextSibling.nextSibling.value;
}

Hope this helps you. Enjoy coding….!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Syed Mujtaba Hassan
Software Developer
Pakistan Pakistan
Syed Mujtaba Hassan
Software Engineer
Intelligentsia Software (Pvt) Ltd Islamabad Pakistan.

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150129.1 | Last Updated 16 Sep 2010
Article Copyright 2010 by Syed Mujtaba Hassan
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid