There isn't the attribute Value
:
<asp:CheckBox ID="CheckBox1" runat="server" />
while on standard HTML this is allowed :
<input type="checkbox" ID="CheckBox1" value="My Valyue" />
why?
The value property sets or returns the value of the value attribute of a checkbox. For checkboxes, the contents of the value property do not appear in the user interface. The value property only has meaning when submitting a form.
If a checkbox is marked or checked, it indicates to true; this means that the user has selected the value. If a checkbox is unmarked or not checked, it indicated to false; this means that the user has not selected the value.
A checkbox can pass one of the two values to this variable - one value for the checked state and another one for the unchecked state.
The Text
property is used to render a label for the checkbox.
The control has an InputAttributes
property that you can add to:
myChk.InputAttributes.Add("value", "My Value");
I believe that if you simply add the value
attribute to the markup, this will also get populated.
You can access the value like so:
myChk.InputAttributes["value"];
To answer the question of why Value
is not a build in attribute to the CheckBox
control:
A CheckBox
in isolation (just by itself) needs no value. By definition it is a boolean and is identified by its ID. All you need to do is check whether it was checked or not.
The value comes into play when you group checkboxes and there is a control for that - the CheckBoxList
that uses ListItem
- each ListItem
does have a Value
property.
Instead of using the asp:CheckBox control, use the html input checkbox, and run it at the server.
<input type="checkbox" id="ck" runat="server" value='<%# Eval("Value") %>' />
<asp:Label ID="lbl" runat="server" AssociatedControlID="ck" Text='<%# Eval("Name") %>'></asp:Label>
Now you can reference it from codebehind as an HtmlInputCheckBox (my latest example is inside a repeater, so I can decorate this substitute for a checkbox list with other elements, like a tool tip image).
foreach (RepeaterItem repeaterItem in repCheckboxes.Items)
{
HtmlInputCheckBox listItem = (HtmlInputCheckBox)repeaterItem.FindControl("ck");
if (listItem.Checked)
{
string val = listItem.Value;
...
I know this does not answer the "why" of the OP, but this comes up high in searches for this exact problem, and this is a good solution. As for why, I think MS goofed by leaving it out, since you don't have control over the html in a CheckBoxList
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With