WB 单选 复选 例子

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

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //绑定数据
        if (!IsPostBack)
        {
            TextDataContext context = new TextDataContext();
            CheckBoxList1.DataSource=context.Nation;
            CheckBoxList1.DataTextField = "Name";//显示的哪一列
            CheckBoxList1.DataValueField = "Code";//他的值是哪一列
            CheckBoxList1.DataBind();//绑定
        }

    }
    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        foreach (ListItem item in CheckBoxList1.Items)
        {
            item.Selected = CheckBox1.Checked;
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    { 
        string zhi = "";
        foreach (ListItem item in CheckBoxList1.Items)
        {
            //去除每一项的值
            if (item.Selected)
            {
                zhi += item.Value.ToString()+",";//把每一项的值拼接到字符串里面
            }  
        }
        //用截取字符串的方法 去掉最后多余的逗号
        zhi = zhi.Substring(0, zhi.Length - 1);

        //拆分字符串  每一个选中都弹一个窗  
        string[] codes;//定义一个字符串的数组
        codes = zhi.Split(','); //每一项里面都是code

        //造JS代码
        string js ="<script type='text/javascript'>";

        for (int i = 0; i < codes.Length; i++)
        {
            js += "alert('" + codes[i] + "');";//便利一下数组 每一条数据都生成一条alert
        }
        js += "</script>";

        Literal1.Text = js;
        //用Literal1 给他附上一段文本 这段文本是JS代码
       // Literal1.Text = "<script type='text/javascript'>alert('"+zhi+"')</script>";
    }
    protected void Button2_Click(object sender, EventArgs e)
    {

    }
}

  

原文地址:https://www.cnblogs.com/zhuxu/p/5048400.html