2013-06-03 70 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

回答