Insert Data Into GridView Using LINQ

Step 1

Open Visual Studio 10 then create an empty website then provide a name such as insert_data_gridview (or whatever you like).

Step 2

Go to your website that will be in your right hand pane, right-click on the project and select "Add New Item". In that you need to select " Web Form". By default the name is "Default.aspx"; change it to "linqgridviewdemo.aspx". Naming is very important in every project, try to keep in the habit, it'll become very helpful in large projects.

Step 3

Again you need to add “SQL Server Database" and "LINQ to SQL classes" from Add New Item and provide a suitable name for both files. They will ask you by prompting whether or not to add a SQL file into the "App_data" folder, make it "Yes". It is good to keep our database inside a secure folder provided by Microsoft, otherwise it can be hacked by SQL Injection or similar attacks.

Step 4

We first design our linqgridviewdemo.aspx page. Open it up and get into the Design section that is showing in the bottom part. Modify the design as in the following:

Step 5

In the left pane of your Visual Studio 10 there is a Server Explorer. Since you added a SQL Server Database, VS 10 automatically made a Database.mdf file for you. Right-click on the table and Add a new table, provide the name as "tbl_data".

Step 6

In that pane you only need to make 2 Stored Procedures named "sp_getdata" and "sp_insertdata".

The following is the code for sp_getdata:

The following is the code for sp_insertdata:

Step 7

We need to add this Stored Procedure to the LINQ file that we added from add new item. Open your LINQ file "DataClasses.dbml". When you open it you see two sections, one is for a relational database and the other is for a simple database, we need to drag all our Stored Procedures into the section of the simple database. Like this:

Step 8

Open the "linqgridviewdemo.cs" file. We need to code now for inserting data into textboxes and when you press the button, the data will be set into the GridView. So go ahead, let's do the code, it's really simple.

  1. public partial class _Default: System.Web.UI.Page  
  2. {  
  3.     DataClassesDataContext ddc = new DataClassesDataContext();  
  4.     protected void Page_Load(object sender, EventArgs e)   
  5.     {  
  6.         refreshdata();  
  7.     }  
  8.     public void refreshdata()   
  9.     {  
  10.         GridView1.DataSource = ddc.sp_getdata();  
  11.         GridView1.DataBind();  
  12.     }  
  13.     protected void Button1_Click(object sender, EventArgs e)  
  14.     {  
  15.         ddc.sp_insertdata(TextBox1.Text, TextBox2.Text, TextBox3.Text);  
  16.         refreshdata();  
  17.     }  
  18. }  
This is it! You can see by pressing Ctrl+Shift+W then filling in all the text boxes and submitting it. You will see all the data will enter into the grid view. I hope you like it.

Thank you for reading! Happy Day.