prashant dhuri prashant dhuri - 14 days ago 4
ASP.NET (C#) Question

How to remove Session datatable row on click of a Button inside Datalist

How to delete data from session datatable using button inside datalist?


This code is to display product added inside shopping cart and bremove button is used to remove that item from datalist

Front End Code

<asp:DataList ID="DataList1" runat="server" Width="100%" HorizontalAlign="Center">
<ItemStyle BorderStyle="Double" />
<ItemTemplate>
<center>
<table class="table" style="border-style: dashed; top: 211px; left: 23px; height: auto; table-layout: fixed; width: 100%;">
<tr>
<td>
<asp:Image ID="Pimg" runat="server" ImageUrl='<%# Eval("Pimg") %>' CssClass="img img-responsive" Height="140px" Width="240px" />
</td>
<td>
<asp:Label ID="Pname" runat="server" Text='<%# Eval("Pname") %>'></asp:Label>
</td>
<td>
<asp:Label ID="Pqty" runat="server" Text='<%# Eval("Pqty") %>'></asp:Label>
</td>
<td>
<asp:Label ID="Price" runat="server" Text='<%# Eval("Price") %>'></asp:Label>
</td>
<td>
<asp:Button ID="bremove" runat="server" Text="Remove" OnClick="bremove_Click" />
</td>
</tr>
</table>
</center>
</ItemTemplate>
</asp:DataList>


Back End Code

protected void bremove_Click(object sender, EventArgs e)
{
int index = DataList1.SelectedIndex;
DataTable dt = Session["AddToCard"] as DataTable;
dt.Rows[index].Delete();
porductlist = dt;
BindData();
Response.Redirect("Default.aspx");
}
public void BindData()
{
DataList1.DataSource = porductlist;
DataList1.DataBind();
}

Answer

Add AcceptChanges()

protected void bremove_Click(object sender, EventArgs e)
{
    int index = DataList1.SelectedIndex;
    DataTable dt = Session["AddToCard"] as DataTable;

    dt.Rows[index].Delete();
    dt.AcceptChanges();

    DataList1.DataSource = dt;
    DataList1.DataBind();

    porductlist = dt;
    BindData();
    Response.Redirect("Default.aspx");
}

But you call BindData() AND redirect, redirecting is not necessary. Unless you want to go to another page in which case the BindData() is not necessary.

UPDATE

To get the correct row number, use a button with a Command, not a Click and send the row number as CommandArgument.

<asp:Button ID="bremove" runat="server" Text="Button" OnCommand="bremove_Command" CommandArgument='<%# Container.ItemIndex %>' />

protected void bremove_Command(object sender, CommandEventArgs e)
{
    int index = Convert.ToInt32(e.CommandArgument);
}