In this article we will learn how to Bind Chekbox List and get the Selected Items from List. We will make a Web application using C#. Let’s start.
- Open Visual Studio. Select New Web Site.
- Name it as you want. My application's name is CheckBoxList_Example.
- First Of All Add Web Form. Go to Solution Explorer > Right Click on the Web Site > Select Add > Add New Item > Select > Web Form and Give the Web Form Name, My We Form Page Name Is CheckList_Page.
- Add Check Box List , Label and Button On CheckList_Page.aspx Page.
- <asp:CheckBoxList ID="CheckboxList1" runat="server" AutoPostBack="false" Width="450px">
- </asp:CheckBoxList>
-
- <asp:Label ID="lblmsg" class="textcls" runat="server"></asp:Label>
-
- <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Show Data" />
- Create a method for Bind the CheckBox List.
- protected void Bind_CheckList()
- {
- List<string> listContents = new List<string>();
- listContents.Add("DehraDun");
- listContents.Add("Shimla");
- listContents.Add("Patna");
- listContents.Add("Mumbai");
- listContents.Add("Delhi");
- listContents.Add("Goa");
- listContents.Add("Chennai");
- listContents.Add("Noida");
- listContents.Add("GuruGram");
-
- CheckboxList1.DataSource = listContents;
- CheckboxList1.DataBind();
-
- }
- Call this Method On PageLoad.
- protected void Page_Load(object sender, EventArgs e)
- {
- if (Page.IsPostBack == false)
- {
- Bind_CheckList();
- }
- }
- Get the selected Item List From CheckBoxList Items and show Selected Items List with Help of Label .
- protected void Button1_Click(object sender, EventArgs e)
- {
- string str = "";
-
- for(int i=0;i<CheckboxList1.Items.Count ;i++)
- {
- if(CheckboxList1.Items[i].Selected==true)
- {
- str += CheckboxList1.Items[i].Text + " ," + "<br/>" ;
- }
-
-
- }
- if(str!="")
- {
- str = str.Substring(0, str.Length - 7);
- lblmsg.Text = "Selected Cities are <br/><br/>" + str;
- }
- }
I hope this is helpful for developing. Thanks.