这是我的绑定代码:
string connection_string = ConfigurationManager.ConnectionStrings["DBC"].ConnectionString;
SqlConnection con = new SqlConnection(connection_string);
con.Open();
SqlDataAdapter dataadapter = new SqlDataAdapter("Select * from stud_table", con);
DataSet ds = new DataSet();
dataadapter.Fill(ds);
CheckBoxList1.DataSource = ds;
CheckBoxList1.DataTextField = "Name";
CheckBoxList1.DataValueField = "Rollno";
CheckBoxList1.DataBind();
con.Open();
按钮代码:
protected void Button2_Click(object sender, EventArgs e)
{
for(int i=0;i<CheckBoxList1.Items.Count ;i++)
{
if (CheckBoxList1.Items[i].Selected == true)
{
CheckBoxList1.Items.RemoveAt(i);
}
}
}
如果我选择项目并单击删除按钮,则应从数据库和屏幕中删除。我该怎么做?
答案 0 :(得分:0)
你走了,希望这会有所帮助:
public partial class Default : System.Web.UI.Page
{
private readonly string connection_string = ConfigurationManager.ConnectionStrings["DBC"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindData();
}
protected void Button2_Click(object sender, EventArgs e)
{
var itemsToDelete = new ListItemCollection();
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected)
itemsToDelete.Add(item);
}
foreach (ListItem item in itemsToDelete)
{
//Assuming your id column is Rollno
DeleteFromDB(item.Value);
CheckBoxList1.Items.Remove(item);
}
}
private void BindData()
{
using (var con = new SqlConnection(connection_string))
{
con.Open();
using (var adapter = new SqlDataAdapter("SELECT * FROM stud_table", con))
{
var ds = new DataSet();
adapter.Fill(ds);
CheckBoxList1.DataSource = ds;
CheckBoxList1.DataTextField = "Name";
CheckBoxList1.DataValueField = "Rollno";
CheckBoxList1.DataBind();
con.Close();
}
}
}
private void DeleteFromDB(string rollNo)
{
int id = 0;
if (Int32.TryParse(rollNo, out id))
{
using (var con = new SqlConnection(connection_string))
{
con.Open();
string commandText = String.Format("DELETE FROM stud_table WHERE Rollno={0}", id);
using (var command = new SqlCommand(commandText, con))
{
command.ExecuteNonQuery();
con.Close();
}
}
}
}
}