CheckBoxList 相关操作

来源:互联网 发布:手机蒙文软件 编辑:程序博客网 时间:2024/06/03 05:05

前台代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Admin_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>CheckBoxList 相关操作</title>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBoxList ID="cklList" runat="server"
            RepeatDirection="Horizontal">
        </asp:CheckBoxList>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>
后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MODEL;
using BLL;

public partial class Admin_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            show();
        }
    }
    public void show()
    {

       //此处查询的是数据库数据
        this.cklList.DataSource = LblManager.GetDataTable();
        this.cklList.DataTextField = "lname";
        this.cklList.DataValueField = "id";
        this.cklList.DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        ///第一种:获取CheckBoxList选中的值
        //string str_Save_cblJL = "";
        //foreach (ListItem li in this.cklList.Items)
        //{
        //    if (li.Selected == true)
        //    {
        //        str_Save_cblJL += li.Value + ",";
        //    }
        //}
        //this.Label1.Text = str_Save_cblJL;
        ///第二种:获取CheckBoxList选中的值
        //string save_cblJL = "";
        //for (int i = 0; i < this.cklList.Items.Count; i++)
        //{
        //    if (this.cklList.Items[i].Selected == true)
        //    {
        //        save_cblJL += this.cklList.Items[i].Value + ",";
        //    }
        //}
        //Label1.Text = save_cblJL;
        ///第三种:从后台给前台CheckBox赋值  C#代码 
        string strapp = "1,2,4,";
        string[] strtemp = strapp.Split(',');
        foreach (string str in strtemp)
        {
            for (int i = 0; i < cklList.Items.Count; i++)
            {
                if (this.cklList.Items[i].Value == str)
                {
                    this.cklList.Items[i].Selected = true;
                }
            }
        }
    }
}

原创粉丝点击