asp.net(C#)中CheckBoxList 绑定及取值(多选)问题
Default.aspx文件<asp:CheckBoxListID="CheckBoxList1"runat="server"></asp:CheckBoxList><a...
Default.aspx文件
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>
<asp:Button ID="Button1" runat="server" Text="添加" OnClick="Button1_Click" />
Default.aspx.cs文件
SqlConnection con = new SqlConnection("server=.;database=db_Trade;uid=sa;pwd=;");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select top 10 * from tb_Speciality", con);
DataSet ds = new DataSet();
sda.Fill(ds);
this.CheckBoxList1.DataSource = ds.Tables[0];
this.CheckBoxList1.DataTextField = "speciality_name";
this.CheckBoxList1.DataValueField = "speciality_id";
this.CheckBoxList1.DataBind();
con.Close();
CheckBoxList已经显示绑定的数据,但是我想把被选中的值(多选)写入数据库,
前台后台都该怎么做啊?先谢谢各位大侠了!
在线等啊 展开
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>
<asp:Button ID="Button1" runat="server" Text="添加" OnClick="Button1_Click" />
Default.aspx.cs文件
SqlConnection con = new SqlConnection("server=.;database=db_Trade;uid=sa;pwd=;");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select top 10 * from tb_Speciality", con);
DataSet ds = new DataSet();
sda.Fill(ds);
this.CheckBoxList1.DataSource = ds.Tables[0];
this.CheckBoxList1.DataTextField = "speciality_name";
this.CheckBoxList1.DataValueField = "speciality_id";
this.CheckBoxList1.DataBind();
con.Close();
CheckBoxList已经显示绑定的数据,但是我想把被选中的值(多选)写入数据库,
前台后台都该怎么做啊?先谢谢各位大侠了!
在线等啊 展开
1个回答
展开全部
for (int index = 0; index < Checkboxlist1.Items.Count; index++)
{
if (Checkboxlist1.Items[index].Selected)
{
if (!Insert(Checkboxlist1.Items[index].ToString()))
{
MessageBox.Show("一条数据插入失败!中断操作!");
return;
}
}
}
//入库方法
private bool Insert(string value)
{
SqlConnection con = new SqlConnection("server=.;database=db_Trade;uid=sa;pwd=;");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into tablename(aa)values('" + value + "')", con);
if (cmd.ExecuteNonQuery() == 1)
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
finally
{
con.Open();
}
}
{
if (Checkboxlist1.Items[index].Selected)
{
if (!Insert(Checkboxlist1.Items[index].ToString()))
{
MessageBox.Show("一条数据插入失败!中断操作!");
return;
}
}
}
//入库方法
private bool Insert(string value)
{
SqlConnection con = new SqlConnection("server=.;database=db_Trade;uid=sa;pwd=;");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into tablename(aa)values('" + value + "')", con);
if (cmd.ExecuteNonQuery() == 1)
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
finally
{
con.Open();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询