无法将Checkboxlist选定项添加到String Array

时间:2014-04-01 17:44:40

标签: c# asp.net arrays checkboxlist

我已经从SqlServer数据库动态填充数据到我的复选框列表..使用代码

ASPX

<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    SqlConnection cn = new SqlConnection(
        ConfigurationManager.ConnectionStrings["testingCS"].ConnectionString);
    cn.Open();
    SqlCommand cmd1 = new SqlCommand("select * from tbl_vehicletypes", cn);
    SqlDataReader dr = cmd1.ExecuteReader();
    if (dr.HasRows) {
        CheckBoxList1.DataSource = dr;
        CheckBoxList1.DataTextField = "typedesc";
        CheckBoxList1.DataValueField = "vehicletypeid";
        CheckBoxList1.DataBind();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    string[] arr = new string[10];

    for (int i = 0; i < CheckBoxList1.Items.Count; i++)
        if (CheckBoxList1.Items[i].Selected==true)
            arr[i] = CheckBoxList1.Items[i].Value;

    foreach (string s in arr)
        Label2.Text += s + "<br />";
    Label2.Text = CheckBoxList1.Items.Count.ToString();
}

我尝试使用for循环和foreach,但它没有成功。所选数据未添加到字符串数组..

请帮忙

2 个答案:

答案 0 :(得分:1)

试试这个

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

foreach(string s in selectedValue)
   Label2.Text += s + "<br />";

答案 1 :(得分:0)

这对我有用,希望它有所帮助!只是一个带有一个项目的演示,但它适用于CheckBoxList中的任意数量的项目。你是如何选中复选框的?

CheckBoxList cbl = new CheckBoxList();

ListItem li = new ListItem("test");
li.Selected = true;
cbl.Items.Add(li);

Label labelTest = new Label();            

string[] test = cbl.Items.Cast<ListItem>().Where(l => l.Selected)
                                          .Select(l => l.Value)
                                          .ToArray();

labelTest.Text = String.Join("<br /", test);