如何从列表中删除选定的行

时间:2015-04-04 08:25:10

标签: c#

这是我的代码,我应该添加什么来删除它不是来自数据库的特定行。 Plz建议我应该在OnRow DeleteCommand中写什么来删除。我是c#的新手,所以Plz建议详细说明。

private List<Cart> PopulateData()
{
   DataTable dt = new DataTable();
   dt = (DataTable)Session["Test"];
   List<Cart> Product = new List<Cart>();
   if (Session["key"] == null)
   {
       foreach (DataRow row in dt.Rows)
       {
           string Quantity = Request.QueryString["Quantity"];
           float f_num = float.Parse(row["ProductPrice"].ToString());
           Cart cr = new Cart();
           Product.Add(new Cart { ProductName = row["ProductName"].ToString(), ProductPrice = f_num, Quantity = Convert.ToInt32(Quantity), Type = row["Type"].ToString() });
       }
   }
   else if(Session["key"]!=null)
   {
       Product = (List<Cart>)Session["key"];
       foreach (DataRow row in dt.Rows)
       {
           string Quantity = Request.QueryString["Quantity"];
           float f_num = float.Parse(row["ProductPrice"].ToString());
           Cart cr = new Cart();
           Product.Add(new Cart { ProductName = row["ProductName"].ToString(), ProductPrice = f_num, Quantity = Convert.ToInt32(Quantity), Type = row["Type"].ToString() });
       }
   }
   Session["key"] = Product.Select(x => new { Quantity = x.Quantity, ProductName = x.ProductName, ProductPrice = x.ProductPrice }).Distinct();
   return Product;
}

private void BindDataList(List<Cart> dt)
{
    gridview1.DataSource = dt;
    gridview1.DataBind();
}

int m = 0;
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // Make sure the current GridViewRow is a data row. 
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Label Subtotal = (Label)e.Row.FindControl("lbltotal");
        //Label lblUnitsInStock = (Label)e.Row.FindControl("lblUnitsInStock");
        m = m + int.Parse(Subtotal.Text);
        //Table tb = new Table();
    }
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        Label lbltotal = (Label)e.Row.FindControl("Subtotal");
        lbltotal.Text = m.ToString();
    }
}

2 个答案:

答案 0 :(得分:0)

假设您只想从网格中删除该行,您可以使用gridview1.DeleteRow(gridview1.SelectedIndex)作为演示here

答案 1 :(得分:0)

if (this.dataGridView1.SelectedRows.Count > 0)
{
    dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
}