[英]how to create Dynamic check-box list with 3 options in C#
我需要創建從數據庫動態填充的復選框列表。 我用單一選項創建此對象沒有問題,但是使用3-有點困惑我。 目前,我有以下代碼創建具有語言名稱的復選框的單個列:
public void CreateCheckBox(DataSet DSDataForCheckBox, string pLangGrp)
{
CheckBoxList chkList = new CheckBoxList();
chkList.ID = "LanguageList";
chkList.AutoPostBack = true;
chkList.DataSource = DSDataForCheckBox;
chkList.DataTextField = "LangName";
chkList.DataValueField = "LangID";
chkList.DataBind();
Panel pLang = new Panel();
if (pLangGrp != "")
{
pLang.GroupingText = pLangGrp;
}
else
{
pLang.GroupingText = "Non Assigned Group";
}
pLang.Controls.Add(chkList);
this.Form.Controls.Add(pLang);
}
需要您的專家幫助。 謝謝
PS:我們在NET 3.5上,所以4.0的許多選項對我來說不可用。
使用中繼器控件或任何基於列表的控件可以實現此目的的一種方法。
這只是為了提供一些想法,您可以進行研究以適合您的需求。
ASPX
<asp:Repeater ID="Repeater1" runat="server" EnableViewState="False">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td class="RowStyle"><%# Eval("LangName") %></td>
<td>
<asp:CheckBoxList ID="chkListLangs" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Text="R" Value="R"></asp:ListItem>
<asp:ListItem Text="W" Value="W"></asp:ListItem>
<asp:ListItem Text="S" Value="S"></asp:ListItem>
</asp:CheckBoxList>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
后面的代碼以獲取選定的值:
protected void btnSubmitLangs_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
CheckBoxList chkListLanguages = (CheckBoxList)item.FindControl("chkListLangs");
List<ListItem> selectedLangs = chkListLanguages.Items.Cast<ListItem>()
.Where(listItem => listItem.Selected)
.ToList();
//Or you can use foreach loop also to get the selected items.
}
}
將一些測試數據分配給中繼器的代碼:
public void AssignLanguageListToRepeater()
{
List<Language> languages = new List<Language>
{
new Language{LangID="1", LangName="English"},
new Language{LangID="2", LangName="Spanish"}
};
Repeater1.DataSource = languages;
Repeater1.DataBind();
}
希望這對您有幫助...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.