开发者

Any Way To get The selected Indices only in CheckBoxList?

开发者 https://www.devze.com 2023-02-07 08:01 出处:网络
I want to get the selected Indices or Items only in checkBox lsit instead of iterating through each item as Like is there in ListBox.

I want to get the selected Indices or Items only in checkBox lsit instead of iterating through each item as Like is there in ListBox.

I am Getting Selected Value In tWo case In this way:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class ChkBxList_2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        string li = "";
        foreach(ListItem lt in CheckBoxList1.Items)
        {
            if(lt.Selected)
            li += lt.Text;

        }
        Response.Write(li);


    }
    protected void Button2_Click(object sender, EventArgs e)
    {

        string li = "";
        foreach (int lt in ListBox1.GetSelectedIndices())
        {
          li += ListBox1.Items[lt].Text;

        }
        Response.Write(li);


    }
}

In ListBox we have the Option To get Seected Only Items is ther开发者_运维知识库e any For Check Box List?


I dont think there is but you could use this extension method that does exactly that:

public List<ListItem> GetSelectedItems(this CheckBoxList checkBoxList)
{
    List<ListItem> list = new List<ListItem>();
    foreach(ListItem lt in checkBoxList)
    {
        if(lt.Selected)
            list.Add(lt);
    }
    return list;
}


//Call it like this
checkBoxList.GetSelectedItems();


You actually answered your own question. There is no way to get the selected only items in the CheckBoxList control, unlike the ListBox control.

This article has an explanation and a work around help method.

http://weblogs.asp.net/jgalloway/archive/2005/10/02/426346.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消