SOLVED: How can I get VALUE from a checkbox in a datalist? Checkboxes have no VALUE.
<asp:DataList
ID='dlTest'
runat='server'
RepeatColumns开发者_如何学编程='2'>
<ItemTemplate>
<asp:HiddenField ID='cbTestID' runat='server' value='<%# Eval("id") %>' />
<asp:CheckBox ID='cbTest' runat='server' /> <%# Eval("name") %><br />
</ItemTemplate>
// CODE BEHIND
foreach (DataListItem cb in dlTest.Items) {
CheckBox chk = (CheckBox)cb.FindControl("cbTest");
HiddenField hf = (HiddenField)cb.FindControl("cbTestID");
if(chk.Checked)
{
Response.Write(hf.Value);
}
You don't have a VALUE for checkbox because it is just a single item, which means it can be either True or False and you can check it like this,
if(myCheckBox.Selected)
{ do this.. or even fire an event when it changed.
or assign some number to some datatype.. }
On the other hand CheckBoxList does have value like any other list which you can get as
CheckBoxList1.SelectedValue
or You can do following two things two with checkboxlist
CheckBoxList1.SelectedIndex
CheckBoxList1.SelectedItem
Try using Text CheckBox attribute/property instead of Value.
<asp:CheckBox ID="cbTest" runat="server" Text="Text from Checkbox"/>
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = cbTest.Text;
}
See it in action: demo
Refer to this article for CheckBoxList (using Text attribute/property) implementation.
Or if you really want to use the Value property of the CheckBox, check this article.
HTH.
精彩评论