Delete records from DataTable using Linq in ASP.Net

sanjay8090
 
on Oct 14, 2019 04:51 AM
Sample_375546.zip
1827 Views

How to delete  100 record from static data table using linq

Download FREE API for Word, Excel and PDF in ASP.Net: Download
pandeyism
 
on Oct 14, 2019 06:30 AM

Hi sanjay8090,

Refer below sample.

HTML

<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
    </Columns>
</asp:GridView>
<asp:Button Text="Delete" runat="server" OnClick="Delete" />

Namespaces

C#

using System.Data;

VB.Net

Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Id");
        dt.Columns.Add("Name");
        dt.Rows.Add(1, "Ajeet");
        dt.Rows.Add(2, "Dharmendra");
        dt.Rows.Add(3, "Ravi");
        dt.Rows.Add(4, "Anirudha");
        GridView1.DataSource = dt;
        GridView1.DataBind();
        ViewState["dt"] = dt;
    }
}

protected void Delete(object sender, EventArgs e)
{
    DataTable dt = ViewState["dt"] as DataTable;
    var result = dt.AsEnumerable().Take(3);
    foreach (var row in result.ToList())
    {
        row.Delete();
    }
    GridView1.DataSource = dt;
    GridView1.DataBind();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As DataTable = New DataTable()
        dt.Columns.Add("Id")
        dt.Columns.Add("Name")
        dt.Rows.Add(1, "Ajeet")
        dt.Rows.Add(2, "Dharmendra")
        dt.Rows.Add(3, "Ravi")
        dt.Rows.Add(4, "Anirudha")
        GridView1.DataSource = dt
        GridView1.DataBind()
        ViewState("dt") = dt
    End If
End Sub

Protected Sub Delete(ByVal sender As Object, ByVal e As EventArgs)
    Dim dt As DataTable = TryCast(ViewState("dt"), DataTable)
    Dim result = dt.AsEnumerable().Take(3)

    For Each row In result.ToList()
        row.Delete()
    Next

    GridView1.DataSource = dt
    GridView1.DataBind()
End Sub

Screenshot