2013-04-10 27 views
1

這是我的綁定代碼:如何刪除在asp.net中綁定的CheckBoxList中的一個項目?

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

在這裏,你走了,希望這有助於:

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(); 
       } 
      } 
     } 
    } 
} 
+0

德尼 - 感謝ü上DeleteFromDB和調試其工作 – divi 2013-04-10 07:09:27

+0

,但它是從CheckBoxList的刪除而不是在數據庫表.. – divi 2013-04-10 07:19:01

+0

將制動點代碼。數據庫中是否存在deleteNo語句 – 2013-04-10 07:22:34

相關問題