asp:CheckBoxList

本文介绍如何在ASP.NET应用程序中使用C#进行数据绑定和数据库操作,包括从数据库检索数据并将其绑定到CheckBoxList控件,以及如何判断CheckBoxList中被选中的项数并进行相应的业务逻辑处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据绑定:

SqlConnection con = new SqlConnection("server=.;database=diancai;uid=sa;pwd=;");
            con.Open();
            //7元荤菜
            SqlCommand cmd1 = new SqlCommand("select * from CaiXinxi where caiShuxing='荤' and caiSpr=0 and (select count(*) from CaiXinxi where caiXingqi like '%" + LabelDay.Text + "%')>0", con);
            SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
            DataSet ds1 = new DataSet();
            da1.Fill(ds1);
            CheckBoxList7hun.DataSource = ds1;
            CheckBoxList7hun.DataTextField = "caiMingcheng";
            CheckBoxList7hun.DataBind();

            con.Close();

 

判断CheckBoxList被选中的数量:

 int count2 = 0;

foreach (ListItem litem in CheckBoxListsu.Items)
            {
                if (litem.Selected)
                {
                    count2 ++;
                }
            }
            if (count2 != 2)
            {
                Response.Write("<script>alert(/"素菜要两份哦!!/");</script>");
                return;
            }

 //选中的是哪两个菜
            string m_strTemp = string.Empty;
             for (int i = 0; i < CheckBoxListsu.Items.Count; i++)//读取CheckBoxList 选中的值,保存起来
             {
                 if (CheckBoxListsu.Items[i].Selected)
                 {
                     m_strTemp += CheckBoxListsu.Items[i].Value + "','";
                 }
             }

当有多个chackbox被选中,写入数据库时:

 

SqlCommand cmd1 = new SqlCommand("insert into Diancai (hun1,su1,su2,yinliao) values('" + CheckBoxList7hun.SelectedValue + "','" + m_strTemp +  CheckBoxListyinliao.SelectedValue + "')", con);
            cmd1.ExecuteNonQuery();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值