Click here to Skip to main content
11,708,312 members (65,606 online)
Click here to Skip to main content

LINQ Demo with ASP.NET Web Application

, 29 Apr 2011 CPOL 117.3K 7.7K 24
Rate this:
Please Sign up or sign in to vote.
A sample application for beginner users who want to start the Linq implementation in ASP.NET

Introduction

This is an ASP.NET Linq demo.

Background

If you have knowledge of bind datagrid and add, update and delete record through the ASP.NET application and no idea about the Linq integration, then this article will give you an idea of how to use Linq.

Using the Code

This is a sample application for beginner users who want to start the Linq implementation with ASP.NET.

Step 1

Create a new Web application project:

Step 2

Create a Web Form:

<asp:Button ID="btnView" runat="server" Text="View" OnClick="btnView_Click" />
    <asp:Button ID="btnAddNew" runat="server" Text="Add New" OnClick="btnAddNew_Click" />
    <table id="tblForm" runat="server">
        <tr>
            <td>Country Name:</td>
            <td><asp:TextBox ID="txtCountryName" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Country Code:</td>
            <td><asp:TextBox ID="txtCountryCode" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Button ID="btnSave" runat="server" Text="Add" 
		OnClick="btnSave_Click" />
                <asp:Button ID="btnUpdate" runat="server" Text="Update" 
		OnClick="btnUpdate_Click" />
                <asp:Button ID="btnCancel" runat="server" Text="Cancel" 
		OnClick="btnCancel_Click" />
            </td>
        </tr>
    </table>
    <table id="tblGrid" runat="server">
        <tr>
            <td><asp:Label ID="lblID" runat="server" Visible="false"></asp:Label>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
		OnRowCommand="GridView1_RowCommand">
                    <Columns>
                        <asp:BoundField DataField="Countryid" HeaderText="ID" />
                        <asp:BoundField DataField="CountryName" 
			HeaderText="Country Name" />
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:LinkButton ID="lnkEdit" runat="server" 
				CommandArgument='<%# Eval("Countryid")%>'
                                    CommandName="cmdEdit" Text="Edlit"></asp:LinkButton>
                                  ---  
                                <asp:LinkButton ID="lnkDelete" runat="server" 
				CommandArgument='<%# Eval("Countryid")%>'
                                    CommandName="cmdDelete" Text="Delete">
			     </asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </td>
        </tr>
    </table>

Step 3

Add a new item – Linq to SQL classes:

Step 4

Create a database table -- tblCountry:

CREATE TABLE [dbo].[tblCountry](
	[Countryid] [int] IDENTITY(1,1) NOT NULL,
	[CountryName] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
	[CountryCode] [nvarchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
	[Status] [nvarchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
	
 CONSTRAINT [PK_tblCountry] PRIMARY KEY CLUSTERED 
(
	[Countryid] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

Step 5

Connect the database to the project:

Step 6

Select the table for Linq table integration:

Step 7

Set database connection string in web.config file:

<appSettings>
  <add key="constr" value="Data Source = machinename\SQLEXPRESS;
	Initial Catalog=test;User ID=tuser; password=tpass"/>
</appSettings>

Step 8

Write Insert record method:

protected void btnSave_Click(object sender, EventArgs e)
        {
            using(DLCountryiesDataContext countries = new DLCountryiesDataContext())
            {
                tblCountry country = new tblCountry
                 {
                     CountryName = txtCountryName.Text.Trim(),
                     CountryCode = txtCountryCode.Text.Trim(),
                     Status = "Active"
                 };
                countries.Connection.ConnectionString = 
		System.Configuration.ConfigurationManager.AppSettings["constr"];
                countries.tblCountries.InsertOnSubmit(country);
                countries.SubmitChanges();
                ViewData();
            }
        }

Step 9

Write method View Records in Gridview:

private void ViewData()
        {
            ClearForm();
            DLCountryiesDataContext db = new DLCountryiesDataContext();
            db.Connection.ConnectionString = 
		System.Configuration.ConfigurationManager.AppSettings["constr"];
            var country =
                from c in db.tblCountries
                select c;

            GridView1.DataSource = country;
            GridView1.DataBind();
        }

Step 10

Write methods for edit and delete records:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "cmdEdit")
            {
                ClearForm();
                DLCountryiesDataContext db = new DLCountryiesDataContext();
                db.Connection.ConnectionString = 
		System.Configuration.ConfigurationManager.AppSettings["constr"];
                var country =
                    from c in db.tblCountries
                    where (c.Countryid == Convert.ToInt32(e.CommandArgument.ToString()))
                    select c;
                lblID.Text = e.CommandArgument.ToString();
                foreach (tblCountry cntry in country)
                {
                    txtCountryName.Text = cntry.CountryName;
                    txtCountryCode.Text = cntry.CountryCode;
                }
                btnSave.Visible = false;
                btnUpdate.Visible = true;
            }
            if (e.CommandName == "cmdDelete")
            {
                DLCountryiesDataContext db = new DLCountryiesDataContext();
                db.Connection.ConnectionString = 
		System.Configuration.ConfigurationManager.AppSettings["constr"];
                var country =
                    from c in db.tblCountries
                    where (c.Countryid == Convert.ToInt32(e.CommandArgument.ToString()))
                    select c;

                db.tblCountries.DeleteAllOnSubmit(country);
                db.SubmitChanges();
                ViewData();
            }
        }

Step 11

Write method for update record:

protected void btnUpdate_Click(object sender, EventArgs e)
        {
            DLCountryiesDataContext db = new DLCountryiesDataContext();
            db.Connection.ConnectionString = 
		System.Configuration.ConfigurationManager.AppSettings["constr"];

            var country = db.tblCountries.Single
		(p => p.Countryid == Convert.ToInt32(lblID.Text));
            country.CountryName = txtCountryName.Text.Trim();
            country.CountryCode = txtCountryCode.Text.Trim();
            db.SubmitChanges();
            ViewData();
        }

Step 12

Common methods for page (it's not mandatory to use in page):

protected void btnView_Click(object sender, EventArgs e)
        {         
            ViewData();
            HideForm();
        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            ShowForm();
            btnSave.Visible = true;
            btnUpdate.Visible = false;            
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {   
            ViewData();
            HideForm();
        }
        
        private void HideForm()
        {
            tblForm.Visible = false;
            tblGrid.Visible = true;
            btnView.Visible = false;
            btnAddNew.Visible = true;            
        }
        
        private void ShowForm()
        {
            tblForm.Visible = true;
            tblGrid.Visible = false;
            btnView.Visible = true;
            btnAddNew.Visible = false;
        }
        
        private void ClearForm()
        {
            txtCountryCode.Text = "";
            txtCountryName.Text = "";
        }

Step 13

Run the project.

End.

History

  • 29th April, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

anrorathod
Web Developer
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionBeginners about Linq Pin
Ajay Shedge18-Jul-14 22:55
professionalAjay Shedge18-Jul-14 22:55 
QuestionReally useful Pin
premkumar.chinnasamy2-Jan-14 4:13
memberpremkumar.chinnasamy2-Jan-14 4:13 
QuestiontblCountries?? Pin
Member 1036238121-Nov-13 12:10
memberMember 1036238121-Nov-13 12:10 
QuestionMy Vote Of 5* Pin
Mas1119-Sep-13 3:05
memberMas1119-Sep-13 3:05 
GeneralMy vote of 2 Pin
alex44019-Jun-13 12:06
memberalex44019-Jun-13 12:06 
Questionconnection error Pin
shekher malik16-Apr-13 20:59
membershekher malik16-Apr-13 20:59 
GeneralMy vote of 5 Pin
Avik Ghosh2221-Feb-13 20:54
memberAvik Ghosh2221-Feb-13 20:54 
QuestionVote of 5 Pin
sjt00311-Dec-12 8:59
membersjt00311-Dec-12 8:59 
AnswerVote of 5 Pin
aarif moh shaikh13-Nov-14 18:16
professionalaarif moh shaikh13-Nov-14 18:16 
QuestionError using DLCountryiesDataContext Pin
Member 800268910-Dec-12 21:18
memberMember 800268910-Dec-12 21:18 
AnswerRe: Error using DLCountryiesDataContext Pin
Hidayat Meman18-Feb-13 2:18
memberHidayat Meman18-Feb-13 2:18 
QuestionStored Procedure Pin
Rohit Pandit28-Nov-12 23:19
memberRohit Pandit28-Nov-12 23:19 
GeneralMy vote of 4 Pin
bhagwat prasad21-Aug-12 2:26
groupbhagwat prasad21-Aug-12 2:26 
GeneralMy vote of 4 Pin
ashwin854426-Mar-12 3:06
memberashwin854426-Mar-12 3:06 
great..
GeneralReally good introduction Pin
Luis E. Serrano G.15-Dec-11 4:19
memberLuis E. Serrano G.15-Dec-11 4:19 
Generalvery nice Pin
amreg3-May-11 14:01
memberamreg3-May-11 14:01 
GeneralMy vote of 3 Pin
MrQuinn1-May-11 5:10
memberMrQuinn1-May-11 5:10 
GeneralRe: My vote of 3 Pin
anrorathod2-May-11 0:23
memberanrorathod2-May-11 0:23 
GeneralMy vote of 3 Pin
Oslec1-May-11 0:27
memberOslec1-May-11 0:27 
GeneralRe: My vote of 3 Pin
anrorathod2-May-11 0:24
memberanrorathod2-May-11 0:24 
General[My vote of 1] Not an article Pin
Mark Nischalke29-Apr-11 8:48
mvpMark Nischalke29-Apr-11 8:48 
GeneralRe: [My vote of 1] Not an article Pin
Oslec1-May-11 0:32
memberOslec1-May-11 0:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150819.1 | Last Updated 29 Apr 2011
Article Copyright 2011 by anrorathod
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid