如何使用 ASP.NET C # 中的 foreach 获取 CheckBoxList 中选定项的值?

我有一个这样的复选框列表:

<asp:CheckBoxList ID="CBLGold" runat="server" CssClass="cbl">
<asp:ListItem Value="TGJU"> TG </asp:ListItem>
<asp:ListItem Value="GOLDOZ"> Gold </asp:ListItem>
<asp:ListItem Value="SILVEROZ"> Silver </asp:ListItem>
<asp:ListItem Value="NERKH"> NE </asp:ListItem>
<asp:ListItem Value="TALA"> Tala </asp:ListItem>
<asp:ListItem Value="YARAN"> Sekeh </asp:ListItem>
</asp:CheckBoxList>

现在我想使用 foreach 从 CheckBoxList 中获取所选项的值,并将这些值放入一个列表中。

334812 次浏览

请注意,我希望代码简短。

List<ListItem> selected = CBLGold.Items.Cast<ListItem>()
.Where(li => li.Selected)
.ToList();

或一个简单的 foreach:

List<ListItem> selected = new List<ListItem>();
foreach (ListItem item in CBLGold.Items)
if (item.Selected) selected.Add(item);

如果你只想要 ListItem.Value:

List<string> selectedValues = CBLGold.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value)
.ToList();

下午好,您总是可以使用一个小 LINQ 来获得选定的列表项目,然后做您想要的结果:

var selected = CBLGold.Items.Cast<ListItem>().Where(x => x.Selected);
// work with selected...
foreach (ListItem item in CBLGold.Items)
{
if (item.Selected)
{
string selectedValue = item.Value;
}
}

根据这里的建议,我添加了一个扩展方法,使用 LINQ 为从 System.Web.UI.WebControls.ListControl继承的任何类型返回所选项的列表。

每个 ListControl对象都具有 ListItemCollection类型的 Items属性。ListItemCollection公开 ListItems的集合,其中每一个都具有 Selected属性。

夏普:

public static IEnumerable<ListItem> GetSelectedItems(this ListControl checkBoxList)
{
return from ListItem li in checkBoxList.Items where li.Selected select li;
}

VisualBasic:

<Extension()> _
Public Function GetSelectedItems(ByVal checkBoxList As ListControl) As IEnumerable(Of ListItem)
Return From li As ListItem In checkBoxList.Items Where li.Selected
End Function

然后,像这样用两种语言中的任意一种:

myCheckBoxList.GetSelectedItems()
string s= string.Empty


for (int i = 0; i < Chkboxlist.Items.Count; i++)


{


if (Chkboxlist.Items[i].Selected)
{
s+= Chkboxlist.Items[i].Value + ";";
}


}
List<string> values =new list<string>();
foreach(ListItem Item in ChkList.Item)
{
if(Item.Selected)
values.Add(item.Value);
}

在我的代码背景中,我在 Page _ Load 事件中从 sql db 创建了一个 checkboxlist,并且在按钮 _ click 事件中完成了 checkboxlist 中的所有 get 值等。

因此,当我选中一些复选框,然后单击按钮时,首先发生的事情是,我的 page _ load 事件重新创建了复选框列表,因此在运行 get 复选框值时没有选中任何复选框..。 我没有在 page _ load 事件中添加 if (! this. IsPostBack)

protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// db query and create checkboxlist and other
SqlConnection dbConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
string query;
try
{
query = "SELECT [name], [mail] FROM [users]";
dbConn.Open();
SqlDataAdapter da = new SqlDataAdapter(query, dbConn);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count != 0)
{
checkboxlist1.DataSource = ds;
checkboxlist1.DataTextField = "name";
checkboxlist1.DataValueField = "mail";
checkboxlist1.DataBind();
}
else
{
Response.Write("No Results found");
}
}
catch (Exception ex)
{
Response.Write("<br>" + ex);
}
finally
{
dbConn.Close();
}
}
}


protected void btnSend_Click(object sender, EventArgs e)
{
string strChkBox = string.Empty;
foreach (ListItem li in checkboxlist1.Value)
{
if (li.Selected == true)
{
strChkBox += li.Value + "; ";
// use only   strChkBox += li + ", ";   if you want the name of each checkbox checked rather then it's value.
}
}
Response.Write(strChkBox);
}

输出和预期的一样,是一个分号分隔的列表,我可以在 mailsend 函数中使用它:

    bill@contoso.com; jeff@corp.inc; sam@dot.net

一个小问题的长答案。请注意,我远不是一个专家在这方面,并知道有更好的解决方案比这个,但它可能有助于一些。

为了在@Tim Schmelter 上加油,用 List<int>代替,

List<string> selectedValues = CBLGold.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value)
.Select(int.Parse)
.ToList();

如果您有一个数据绑定 checklistbox,那么获取 item(j).Selected将不起作用,因为该控件没有选定的属性。如果您清除了 Select,即 on Load,那么显然它现在理解了 item(j).selected

我喜欢使用这个简单的方法来获取选定的值并将它们连接到一个字符串中

private string JoinCBLSelectedValues(CheckBoxList cbl, string separator = "")
{
return string.Join(separator, cbl.Items.Cast<ListItem>().Where(li => li.Selected).ToList());
}

只是为了以防万一,您想存储选定的值在单列中由 ,分隔,然后您可以使用下面的方法

string selectedItems = String.Join(",", CBLGold.Items.OfType<ListItem>().Where(r => r.Selected).Select(r => r.Value));

如果要存储文本而不是值,则 将 r 值更改为 r 文本