我需要从GridView中删除一行,我使用了一种不同的方法,所有的操作都是在代码后面完成的。我尝试在用户单击“删除”链接按钮时删除行,但行行没有被删除,我尝试了在行中删除事件,但我收到了堆栈溢出异常。
添加列名:
DataTable dtToGrid = new DataTable();
DataColumn dc = dtToGrid.Columns.Add("S.No", typeof(int));
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dtToGrid.Columns.Add("ItemName", typeof(string));
dtToGrid.Columns.Add("Quantity", typeof(string));
dtToGrid.Columns.Add("Unit", typeof(string));
dtToGrid.Columns.Add("RatePer Unit", typeof(string));
dtToGrid.Columns.Add("Amount", typeof(string));
Session["dtToGrid"] = dtToGrid;
添加行值:
double sum = 0;
grd.Visible = true;
DataTable dtToGrid = (DataTable)Session["dtToGrid"];
DataRow drToGrid = dtToGrid.NewRow();
drToGrid["ItemName"] =ddlProduct.SelectedItem.Value;
drToGrid["Quantity"] = txtQty.Text;
drToGrid["Unit"]=Unit.Value;
drToGrid["RatePer Unit"]=costperunit.Value;
drToGrid["Amount"]=txtAmount.Text;
dtToGrid.Rows.Add(drToGrid);
grd.DataSource = dtToGrid;
grd.DataBind();
for (int x = 0; x < grd.Rows.Count; x++)
{
sum += Convert.ToDouble(grd.Rows[x].Cells[5].Text);
}
if (totalAmountINcludingTax.Text == " ")
{
sum = (sum * Convert.ToDouble(Tax.Value)) / 100 + sum;
totalAmountINcludingTax.Text = sum.ToString();
}
else
{
sum = (sum * Convert.ToDouble(Tax.Value)) / 100 +Convert.ToDouble( totalAmountINcludingTax.Text);
totalAmountINcludingTax.Text = sum.ToString();
}
行删除:
protected void grd_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int Prod_Id = Convert.ToInt32(e.CommandArgument);
grd.DeleteRow(Prod_Id);
}
}
.aspx的:
<asp:GridView ID="grd" runat="server" AutoGenerateColumns="true"
onrowdeleting="grd_RowDeleting" onrowcommand="grd_RowCommand">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbtnDelete" runat="server" CommandName="delete" title="Delete"
OnClientClick="return confirm('Do you Want to Delete this Record?');">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
答案 0 :(得分:1)
为什么不在Delete Row上执行与Add Row相同的逻辑。 基本上找到要删除的数据行,从数据表中删除并重新绑定。
protected void grd_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int Prod_Id = Convert.ToInt32(e.CommandArgument);
DataTable dtToGrid = (DataTable)Session["dtToGrid"];
DataRow rowToBeDeleted = dtToGrid.Rows.Where(r=>r["Prod_Id"] == Prod_Id.ToString());
if (rowToBeDeleted != null)
{
dtToGrid.Rows.Remove(rowToBeDeleted);
grd.DataSource = dtToGrid;
grd.DataBind();
// do your summation logic.
}
}
}