Using the approach shown in the question here, I am able to get the selected items values from my CheckBoxList
:
var selectedCheckBoxItems = from key in Request.Form.AllKeys
where key.Contains(cbl.ID)
select Request.Form.Get(key);
I can then iterate over the results:
foreach (var item in selectedCheckBoxItems)
{
}
The problem is that item
is just the posted value, which for a checkbox, is simply the string "on".
I need to be able to determine which item is "on", either by index or some other method.
Question: How do I determine which items in the CheckBoxList
are selected, using Request.Form
?
Here is my CheckBoxList definition:
<asp:CheckBoxList runat="server" ID="cblAnimalType" SelectionMode="Multiple" DataTextField="OptionText" DataValueField="OptionId" AutoPostBack="True"/>
Items are added to the list from code behind:
DataTable dt = GetData(SqlGetListOptions, paramList);
cbl.DataSource = dt;
cbl.DataBind();
The other important thing to know is that ViewStateMode="Disabled"
, so I must use Request.Form
to get the selected items.
In response to a comment, here is how the HTML for the CheckBoxList renders:
@Leopard pointed out that he sees values rendered in the HTML which is not occurring in my situation. AdamE's answer to this question explains why. I have the following line in web.config:
<pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
which explains why I see "on" instead of the actual value of the selected items. I am not able to just yank the compatibility out of web.config without verifying it won't break something else, but it appears that if that setting is safe to remove, the checkbox list values will be accessible from codebehind.
ViewStateMode="Enabled"
then getting the checked state of the items ofCheckListBox
works fine? – YeaDataValueField
for all items in theCheckBoxList
? – NaceAutoPostBack="true"
on checkboxlist ? – Eloiseloisacbl.DataBind()
? – FluorLoadListOptions(CheckBoxList cbl, string listName)
which is called inPage_Load
– Paraformaldehyde