Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can't set a value on a asp:CheckBox?

Tags:

c#

.net

checkbox

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?

like image 351
markzzz Avatar asked Mar 07 '12 09:03

markzzz


People also ask

Can we assign value to checkbox?

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.

When a checkbox is selected what will be its value?

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.

How many values a check box can have?

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.


2 Answers

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.

like image 51
Oded Avatar answered Oct 12 '22 22:10

Oded


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

like image 38
user1689571 Avatar answered Oct 12 '22 22:10

user1689571