C# 为什么我不能在 asp:CheckBox 上设置值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9599240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why I can't set a value on a asp:CheckBox?
提问by markzzz
There isn't the attribute Value:
没有属性Value:
<asp:CheckBox ID="CheckBox1" runat="server" />
while on standard HTML this is allowed :
而在标准 HTML 上,这是允许的:
<input type="checkbox" ID="CheckBox1" value="My Valyue" />
why?
为什么?
采纳答案by Oded
The Textproperty is used to render a label for the checkbox.
该Text属性用于呈现复选框的标签。
The control has an InputAttributesproperty that you can add to:
该控件具有InputAttributes您可以添加到的属性:
myChk.InputAttributes.Add("value", "My Value");
I believe that if you simply add the valueattribute to the markup, this will also get populated.
我相信,如果您只是将value属性添加到标记中,它也会被填充。
You can access the value like so:
您可以像这样访问该值:
myChk.InputAttributes["value"];
To answer the question of whyValueis not a build in attribute to the CheckBoxcontrol:
要回答为什么Value不是CheckBox控件的内置属性的问题:
A CheckBoxin 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.
一个CheckBox孤立的(就其本身而言)不需要任何值。根据定义,它是一个布尔值,并由其 ID 标识。您需要做的就是检查它是否被选中。
The value comes into play when you groupcheckboxes and there is a control for that - the CheckBoxListthat uses ListItem- each ListItemdoes have a Valueproperty.
当您对复选框进行分组时,该值就会发挥作用,并且有一个控件 -CheckBoxList使用的ListItem- 每个ListItem都有一个Value属性。
回答by user1689571
Instead of using the asp:CheckBox control, use the html input checkbox, and run it at the server.
不要使用 asp:CheckBox 控件,而是使用 html 输入复选框,并在服务器上运行它。
<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).
现在,您可以从代码隐藏中将其作为 HtmlInputCheckBox 引用(我的最新示例在转发器中,因此我可以用其他元素(例如工具提示图像)来装饰此复选框列表的替代品)。
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
我知道这不能回答 OP 的“为什么”,但这在搜索这个确切问题时出现的频率很高,这是一个很好的解决方案。至于为什么,我认为 MS 把它遗漏了,因为你无法控制 CheckBoxList 中的 html

