Simple Tutorial with example of using LINQ to SQL in ASP.Net Website using C#


This article covers the basics of adding and generating dbml classes, connecting to database, adding Table entities and Stored Procedures


In this article I will explain a simple tutorial with example to integrate LINQ to SQL Framework (dbml classes) in ASP.Net using C# and VB.Net.
This article covers the basics of adding and generating dbml classes, connecting to database, adding Table entities and Stored Procedures.
 
HTML Markup
Below is an ASP.Net GridView with some fields from the Customers Table of the Northwind Database.
<asp:GridView ID="gvCustomers" CssClass="Grid" runat="server" AutoGenerateColumns="false"
    PageSize="10" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging">
    <Columns>
        <asp:BoundField DataField="CustomerId" HeaderText="Customer Id" />
        <asp:BoundField DataField="ContactName" HeaderText="Contact Name" />
        <asp:BoundField DataField="City" HeaderText="City" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>
 
 Stored Procedures
I am making use of a Stored Procedure that will get the records from the Customers Table of the Northwind database.
CREATE PROCEDURE [GetCustomers]
AS
BEGIN
      SELECT [CustomerID]
      ,[CompanyName]
      ,[ContactName]
      ,[City]
      ,[Country]
      FROM [Customers]
END
 
 Binding the GridView using LINQ to SQL Framework
This is fairly simple, you will need to create an object of the Data Context of the DBML
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.PopulateCustomers();
    }
}
 
private void PopulateCustomers()
{
    CustomersDataContext ctx = new CustomersDataContext();
    gvCustomers.DataSource = ctx.GetCustomers();
    gvCustomers.DataBind();
}
 
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gvCustomers.PageIndex = e.NewPageIndex;
    this.PopulateCustomers();
}
 

Comments

Popular posts from this blog

Automatically send Birthday email using C#.Net

Drag and Drop multiple File upload using jQuery AJAX in ASP.Net using C# and VB.Net

Difference between each and map in jquery