如何把CheckBoxList中选中的项目的文本添加到数据库的表中

如题所述

table1和table2都有两个字段ID,data。
以下代码是将table1绑定到CheckBoxList控件里。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.CheckBoxListBind();
}
}
public void CheckBoxListBind()
{
SqlConnection con = DB.creatconnection();
con.Open();
SqlCommand cmd = new SqlCommand("select * from table1", con);
this.CheckBoxList1.DataTextField = "data";
this.CheckBoxList1.DataValueField = "ID";
this.CheckBoxList1.DataSource = cmd.ExecuteReader();
this.CheckBoxList1.DataBind();
}
以下代码是将CheckBoxList控件所选的值插入到table2里。
protected void Button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < this.CheckBoxList1.Items.Count; i++)
{
if (this.CheckBoxList1.Items[i].Selected)
{
int j = i + 1;
string CheckBoxListData =Convert.ToString( this.CheckBoxList1.Items[i].Value);
SqlConnection con = DB.creatconnection();
con.Open();
SqlCommand cmd = new SqlCommand("insert into table2 (data)values('" + CheckBoxListData + "')", con);
cmd.ExecuteNonQuery();
Response.Write("插入成功。");
}
}
}
另外,站长团上有产品团购,便宜有保证
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-05-05
selectvalue就是选中的值,然后通过你的添加方法加入就好了
第2个回答  2011-05-05
添加一个SQLDatasource然后配置数据源,然后在SQLDatasourse属性中的InsertQuery中写入相关插入SQL语句,语句中的要插入字段 字段=@字段,然后刷新参数,那个参数右边的参数源选择你你那个CheckboxList

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网