Tuesday, August 14, 2007

Assigning a value to an ASP.Net CheckBox

Unlike the html checkbox, the ASP.Net CheckBox control does not have a value property. However, you can add attributes via markup as well as pragmatically via code.

Markup:
<asp:checkbox id="CheckBox1" runat="server" value="'<%# Eval("ValueColumn") >' />
<asp:checkbox id="CheckBox2" runat="server" value="'2'">

Only Eval can be used to bind to "custom" attributes, as compared to properties built into the control which also work with Bind

Code:
CheckBox2.Attributes.Add("Value", 2);
The "Add" method add takes two parameters. The first parameter is the name of the attribute . The second parameter is the value for this attribute.

This adds a server accessible attribute for the value, the attributes collection is maintained via the viewstate. However the CheckBox control does not render the value attributed (it actually removes the attribute during the render event phase.

However, if you want to add the attribute so it is rendered via html then the checkbox has a property called InputAttributes, adding properties to this collection will always be rendered in the html.

Code:
CheckBox2.InputAttributes.Add("Value", 2);