asp.net checkboxlist selected values linq
asp.net checkboxlist allow to select multiple items. in this example we see how to get the checkboxlist
selected items. here we uses a simple linq query. when someone select an item from checkboxlist it will autopostback the page.
then the linq query perform a query to get selected items list. after that a label control shows the checkboxlist selected items
text and value by foreach loop.
checkboxlist-selected-values-linq.aspx
<%@ Page Language="C#" AutoEventWireup="true"%>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
CheckBoxList1.Items.Add(new ListItem("Laughing Gull", "1"));
CheckBoxList1.Items.Add(new ListItem("Swallow-tailed Gull", "2"));
CheckBoxList1.Items.Add(new ListItem("Caspian Tern", "3"));
CheckBoxList1.Items.Add(new ListItem("Roseate Tern", "4"));
CheckBoxList1.Items.Add(new ListItem("Antarctic Tern", "5"));
}
}
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
// linq query to find selected items from checkboxlist
var items = from ListItem li in CheckBoxList1.Items
where li.Selected == true
select li;
Label1.Text = "you checked item(s).....<br />";
foreach (ListItem li in items)
{
Label1.Text += "text: " + li.Text;
Label1.Text += " <br /> value: " + li.Value + "<br /><br />";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net checkboxlist selected values linq</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
asp.net example - checkboxlist selected values linq
</h2>
<hr width="550" align="left" color="Gainsboro" />
<asp:Label
ID="Label1"
runat="server"
Text="check item(s) from checkboxlist."
Font-Size="Medium"
Width="350"
>
</asp:Label>
<br /><br />
<div class="block">
<asp:CheckBoxList
ID="CheckBoxList1"
runat="server"
RepeatLayout="Table"
RepeatColumns="2"
AutoPostBack="true"
OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged"
>
</asp:CheckBoxList>
</div>
</div>
</form>
</body>
</html>


- How to sort DropDownList items
- How to sort DropDownList items alphabetically
- How to sort DropDownList items by text
- How to set ListBox alternate item text and background color
- How to select all items in a CheckBoxList
- How to retrieve multiple selected values from CheckBoxList
- How to create a horizontal CheckBoxList
- How to get CheckBoxList checked items
- How to set default checked items in CheckBoxList
- How to set the maximum limit of selection in a CheckBoxList