Asp.net, Webforms, c# 4.8: I have a page with a ListView control that contains checkboxes. In the postback, I need to loop through the list and get the IDs of all the checkboxes that were checked, but I dont know how to assign the ID to the checkboxes when the page is generated, and how to loop through the list to get these IDs in the postback. Can someone please explain?
Here's my html:
<asp:ListView ID="CategoryCheckList" runat="server" class="CListStyle"
GroupItemCount="3" ItemPlaceholderID="itemsGoHere"
GroupPlaceholderID="groupsGoHere">
<LayoutTemplate>
<table>
<asp:PlaceHolder runat="server" ID="groupsGoHere"></asp:PlaceHolder>
</table>
</LayoutTemplate>
<GroupTemplate>
<tr>
<asp:PlaceHolder runat="server" ID="itemsGoHere"></asp:PlaceHolder>
</tr>
</GroupTemplate>
<ItemTemplate >
<td><asp:CheckBox id="itemCheckBox" runat="server" /></td>
<td>
<div class="checkboxlist-wrapper">
<asp:Label CssClass="checkboxlist-categories" ID="itemCheckBoxLabel" runat="server" Text='<%# Eval("CategoryName")%>'></asp:Label>
</div>
</td>
</ItemTemplate>
</asp:ListView>
And here's the codebehind:
public partial class WebForm1 : System.Web.UI.Page
{
private List<Category> _categories;
protected void Page_Load(object sender, EventArgs e)
{
LoadCategories();
}
void LoadCategories()
{
List<Category> list = new List<Category>();
list.Add(new Category { CatId = new Guid(), CategoryName = "xxxx" });
list.Add(new Category { CatId = new Guid(), CategoryName = "wwwww" });
list.Add(new Category { CatId = new Guid(), CategoryName = "rrrrr rrrrr" });
list.Add(new Category { CatId = new Guid(), CategoryName = "yyyyy yyyy" });
list.Add(new Category { CatId = new Guid(), CategoryName = "4444444" });
list.Add(new Category { CatId = new Guid(), CategoryName = "hhhhhhhh hhhhhh hhhhhh" });
list.Add(new Category { CatId = new Guid(), CategoryName = "qq" });
list.Add(new Category { CatId = new Guid(), CategoryName = "xx66 666xx" });
_categories = list;
CategoryCheckList.DataSource = _categories;
CategoryCheckList.DataBind();
}
public List<Category> Categories { get => _categories; set => _categories = value; }
public List<Category> GetData()
{
return Categories;
}
}
public class Category
{
public Guid CatId { get; set; }
public string CategoryName { get; set; }
public bool IsChecked { get; set; }
}
Thank you.