Gridview 动态添加行

时间:2022-04-11 13:45:28

/// <summary>

/// 首次加载绑定

/// </summary>

private void DataLoad()         {

list.Add(new Product());

this.GVProduct.DataSource = list;

this.GVProduct.DataBind();

ViewState["list"] = list;

}

/// <summary>

/// 添加行

/// </summary>

private void AddRow()         {

list = (List<Product>)ViewState["list"];

for (int i = 0; i <  this.GVProduct.Rows.Count; i++)         {

Product mod = new Product();

mod.People = int.Parse((GVProduct.Rows[i].Cells[3].FindControl("txtPeople") as TextBox).Text.ToString());

mod.Price = int.Parse((GVProduct.Rows[i].Cells[1].FindControl("txtPrice") as TextBox).Text.ToString());

mod.Size = int.Parse((GVProduct.Rows[i].Cells[3].FindControl("txtSize") as TextBox).Text.ToString());

list.Add(mod);

}

list.Add(new Product());

ViewState["list"] = list;

this.GVProduct.DataSource = list;

this.GVProduct.DataBind();               }

/// <summary>

/// 删除行

/// </summary>

private void DeleteRow() {

list = (List<Product>)ViewState["list"];

for (int i = this.GVProduct.Rows.Count - 1; i >= 0; i--)             {

list[i].People = int.Parse((GVProduct.Rows[i].Cells[3].FindControl("txtPeople") as TextBox).Text.ToString());

list[i].Price = int.Parse((GVProduct.Rows[i].Cells[1].FindControl("txtPrice") as TextBox).Text.ToString());

list[i].Size = int.Parse((GVProduct.Rows[i].Cells[3].FindControl("txtSize") as TextBox).Text.ToString());

CheckBox ck = GVProduct.Rows[i].FindControl("ckitem") as CheckBox;

if (ck.Checked)        {

list.RemoveAt(i);

}

ViewState["list"] = list;

GVProduct.DataSource = list;

GVProduct.DataBind();

}

}