2013-06-03 69 views
0

我遇到了刪除gridview行的問題。我通過點擊添加按鈕,在下拉列表中選擇值,然後填充我GridView控件,值會在我的gridview的加入,這裏是我的代碼:在Gridview中刪除行

在我的aspx:

<asp:GridView ID="GridView1" runat="server" 
      CssClass="mGrid" EmptyDataText = "There are no records to display"> 
      <Columns> 
       <asp:TemplateField ItemStyle-Width="10"> 
     <HeaderTemplate> 

     </HeaderTemplate> 
     <ItemTemplate> 
      <asp:CheckBox ID="CheckBox1" runat="server"/> 
     </ItemTemplate> 
    </asp:TemplateField> 

      </Columns> 
</asp:GridView> 

在我後面的代碼:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
     DataSet ds = new DataSet(); 
     DataTable dt = new DataTable(); 
     DataColumn dc = new DataColumn("Id"); 
     DataColumn dc1 = new DataColumn("Name"); 
     //DataColumn dc2 = new DataColumn("Id"); 

     dt.Columns.Add(dc); 
     dt.Columns.Add(dc1); 
     // dt.Columns.Add(dc2); 
     ds.Tables.Add(dt); 
     Session["data"] = ds; 
     GridView1.DataBind(); 
    } 
} 

protected void btnSave_Click(object sender, EventArgs e) 
{ 
    SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True"); 
    con.Open(); 

    foreach (GridViewRow row in GridView1.Rows) 
    { 
     SqlCommand cmdd = new SqlCommand("Insert into Profile (Id, profile_Id)VALUES(@id, @pid)", con); 
     cmdd.CommandType = System.Data.CommandType.Text; 
     cmdd.Parameters.AddWithValue("@id", row.Cells[1].Text); 
     cmdd.Parameters.AddWithValue("@pid", txtbid.Text); 
     cmdd.ExecuteNonQuery(); 
    } 
} 

protected void btnAdd_Click(object sender, EventArgs e) 
{ 
    DataSet ds = (DataSet)Session["data"]; 
    DataRow dr = ds.Tables[0].NewRow(); 
    dr[0] = DropDownList1.Text.Trim(); 
    dr[1] = DropDownList1.SelectedItem; 
    //dr[2] = txtId.Text.Trim(); 
    ds.Tables[0].Rows.Add(dr); 
    GridView1.DataSource = ds; 
    GridView1.DataBind(); 
} 

現在,我想使用此代碼刪除我的GridView檢查行:

protected void btnRemove_Click(object sender, EventArgs e) 
{ 
    ArrayList del = new ArrayList(); 

    foreach (GridViewRow row in GridView1.Rows) 
    { 
     if (row.RowType == DataControlRowType.DataRow) 
     { 
      CheckBox chkDelete = (CheckBox)row.Cells[0].FindControl("CheckBox1"); 

      if (chkDelete != null) 
      { 
       if (chkDelete.Checked) 
       { 

        string id = row.Cells[1].Text; 
        del.Add(id); 
       } 
      } 
     } 
    } 
    GridView1.DataBind(); 
} 

通過上面的btnRemove代碼,如果我點擊它,它會刪除我的gridview的所有值甚至未選中行,我要的是剛剛選中的行不是全部。是否有任何其他簡單的方法來刪除GridView中的行比使用複選框?我正在使用c#與asp.net。

+0

請出示您擁有actualy刪除在德爾的項目的代碼 - ArrayList中 –

+0

在代碼的第3節最裏面的巢是什麼的productId?你的意思是ID嗎? – deepee1

回答