16 August 2014

Read or Write connection strings in web.config file using asp.net

Introduction:

In this article I will explain how to read or write connection strings in web.config file using asp.net.



Description:

In Previous article I explained clearly about Encrypt or Decrypt connection strings in web.config file using asp.net. Now I will explain how to write connection strings in web.config file and how to read connection strings from web.config file using asp.net. 

I have one web application that contains many pages and each page contains relationship with database connection to get data from database and display it on page because of that I need to write database connections for each page to interact with database. Now the server name or credentials of database server has changed in that situation it will create problem because we need to modify the database connections of each page using asp.net. 
To avoid this situation it would be better if we place connection string in one place and reuse it in every page wherever we need to connect to SQL Server. Web.config is the best place to store the connection strings in asp.net and it would be safer place to store the connection strings instead of writing connection strings in every web page.
Now we want to add connection string in web.config file for that first create new website using visual studio after that create new website open web.config file and search for “connectionStrings” and add new item in connectionStrings section
After open web.config file in application and add sample db connection in connectionStrings section like this 
<connectionStrings>
<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient"/>
</connectionStrings >
Example of declaring connectionStrings in web.config file like this
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System.Data.SqlClient"/>
</connectionStrings >
Here to access my database server there is no need of username and password for that reason I didn’t enter username and password in connection string.
After add dbconnection in connectionString we need to write the some code in our codebehind file to get connection string from web.config file for that add following namespace in codebehind file and write the following code
using System.Configuration;
 This namespace is used to get configuration section details from web.config file.
After add namespaces write the following code in code behind
C# code
using System;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{   
//Get connection string from web.config file
string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
//create new sqlconnection and connection to database by using connection string from web.config file
SqlConnection con = new SqlConnection(strcon);
con.Open();
}
}
VB.NET
Imports System.Data.SqlClient
Imports System.Configuration
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'Get connection string from web.config file
Dim strcon As String = ConfigurationManager.ConnectionStrings("dbconnection").ConnectionString
'create new sqlconnection and connection to database by using connection string from web.config file
Dim con As New SqlConnection(strcon)
con.Open()
End Sub
End Class
Here we stored our database connection string in web.config file it was not secured if we want to encrypt the connection string in web.config file check this post encrypt or decrypt connection string in web.config file.

11 August 2014

How to use ValidationSummary control in asp.net

ValidationSummary example: how to use ValidationSummary control in asp.net
ValidationSummary control allow us to display summary of all validation errors. we can display validation errors summary inline of a web page or a message box or both by using ShowMessageBox and ShowSummary property value true or false. we can display validation messages as bulleted list, single paragraph or only list based on DisplayMode. we can set a header text for validation summary. asp.net validationsummary control have many properties to design the error messages text as like fore color, back color, border color, border style, border width, theme, skin and after all css class.

validationsummary allow to summarize of all validation error messages from all validators in a single location. this example show you how can we display all validation error messages as summary using validationsummary control. here we uses three text box and make them required field using requiredfieldvalidator control. when someone submit form without entering textboxes value, he got a validation error messages summary in one location as bulleted list. 
 
ValidationSummaryExample.aspx
  1. <%@ Page Language="C#" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <script runat="server">  
  6.     protected void Button1_Click(object sender, System.EventArgs e) {  
  7.         Label1.Text = "Your Country: " +  
  8.             TextBox1.Text.ToString() +  
  9.             "<br />Region: " +  
  10.             TextBox2.Text.ToString() +  
  11.             "<br />City: " +  
  12.             TextBox3.Text.ToString();  
  13.     }  
  14. </script>  
  15.   
  16. <html xmlns="http://www.w3.org/1999/xhtml">  
  17. <head runat="server">  
  18.     <title>ValidationSummary example: how to use ValidationSummary control in asp.net</title>  
  19. </head>  
  20. <body>  
  21.     <form id="form1" runat="server">  
  22.     <div>  
  23.         <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="BlueViolet"></asp:Label>  
  24.         <br /><br />  
  25.         <asp:Label ID="Label2" runat="server" Text="Country Name" AssociatedControlID="TextBox1"></asp:Label>  
  26.         <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
  27.         <asp:RequiredFieldValidator  
  28.              ID="RequiredFieldValidator1"  
  29.              runat="server"  
  30.              ControlToValidate="TextBox1"  
  31.              ErrorMessage='Input Country!'  
  32.              EnableClientScript="true"  
  33.              SetFocusOnError="true"  
  34.              Text="*"  
  35.              >  
  36.         </asp:RequiredFieldValidator>  
  37.         <br />  
  38.   
  39.         <asp:Label ID="Label3" runat="server" Text="Region Name" AssociatedControlID="TextBox2"></asp:Label>  
  40.         <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
  41.         <asp:RequiredFieldValidator  
  42.              ID="RequiredFieldValidator2"  
  43.              runat="server"  
  44.              ControlToValidate="TextBox2"  
  45.              ErrorMessage='Input Region!'  
  46.              EnableClientScript="true"  
  47.              SetFocusOnError="true"  
  48.              Text="*"  
  49.              >  
  50.         </asp:RequiredFieldValidator>  
  51.         <br />  
  52.           
  53.         <asp:Label ID="Label4" runat="server" Text="City Name" AssociatedControlID="TextBox3"></asp:Label>  
  54.         <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>  
  55.         <asp:RequiredFieldValidator  
  56.              ID="RequiredFieldValidator3"  
  57.              runat="server"  
  58.              ControlToValidate="TextBox3"  
  59.              ErrorMessage='Input Region!'  
  60.              EnableClientScript="true"  
  61.              SetFocusOnError="true"  
  62.              Text="*"  
  63.              >  
  64.         </asp:RequiredFieldValidator>  
  65.         <br />  
  66.         <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />  
  67.         <br /><br />  
  68.         <asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="Following error occurs:" ShowMessageBox="false" DisplayMode="BulletList" ShowSummary="true" />  
  69.     </div>  
  70.     </form>  
  71. </body>  
  72. </html> 
 

09 August 2014

Difference between char varchar and nvarchar in sql server

Introduction:


In this article I will explain what is the difference between char, varchar and nvarchar in SQL Server.

Description:

In previous post I explained many articles relating to SQL Server. Now I will explain the differences between char, varchar and nvarchar in SQL Server. Actually one of blog reader has asked me question regarding differences between varchar and nvarchar at that time I decided it’s better to write article on this topic.
Char DataType
Char datatype which is used to store fixed length of characters. Suppose if we declared char(50) it will allocates memory for 50 characters. Once we declare char(50) and insert only 10 characters of word then only 10 characters of memory will be used and other 40 characters of memory will be wasted.

varchar DataType
Varchar means variable characters and it is used to store non-unicode characters. It will allocate the memory based on number characters inserted. Suppose if we declared varchar(50) it will allocates memory of 0 characters at the time of declaration. Once we declare varchar(50) and insert only 10 characters of word it will allocate memory for only 10 characters.

04 April 2014

Introduction to Asp.Net Page Life Cycle

In this example, I am trying to help you to give fair ideas about the life cycle of ASP.NET Page.

Following are the steps which occur when we request an ASPX page: -

The browser sends the request to the web server. Let’s assume that the web server at the other end is IIS. Once IIS receives the request he looks on which engine can serve this request.
When I mean engine means the DLL who can parse this page or compile and send a response back to browser. Which request to map to be decided by file extension of the page requested.
Depending on file extension following are some mapping
  1. .aspx, for ASP.NET Web pages
  2. .asmx, for ASP.NET Web services
  3. .config, for ASP.NET configuration files
  4. .ashx, for custom ASP.NET HTTP handlers
  5. .rem, for remoting resources etc.
 
You can also configure the extension mapping to which engine it can route by using the IIS engine.
Example an ASP page will be sent to old classic ASP.DLL to compile. While .ASPX pages will be routed to ASP.NET engine for compilation.
As this article mainly will target ASP.NET we will look in to how ASP.NET pages that is ASPX pages generation sequence occurs. Once IIS passes the request to ASP.NET engine page has to go through two section HTTP module section and HTTP handler section. Both these section have there own work to be done in order that the page is properly compiled and sent to the IIS. HTTP modules inspect the incoming request and depending on that they can change the internal workflow of the request. HTTP handler actually compiles the page and generates output. If you see your machine.config file you will see following section of HTTP modules

Can you explain in brief how the ASP.NET authentication process works?

ASP.NET does not run by itself it runs inside the process of IIS. So there are two authentication layers which exist in ASP.NET system. First authentication happens at the IIS level and then at the ASP.NET level depending on the WEB.CONFIG file.

Below is how the whole process works:-

IIS first checks to make sure the incoming request comes from an IP address that is allowed access to the domain. If not it denies the request.
 
Next IIS performs its own user authentication if it is configured to do so. By default IIS allows anonymous access, so requests are automatically authenticated, but you can change this default on a per – application basis with in IIS
If the request is passed to ASP.Net with an authenticated user, ASP.Net checks to see whether impersonation is enabled. If impersonation is enabled, ASP.Net acts as though it were the authenticated user. If not ASP.Net acts with its own configured account.
Finally the identity from step 3 is used to request resources from the operating system. If ASP.Net authentication can obtain all the necessary resources it grants the users request otherwise it is denied. Resources can include much more than just the ASP.Net page itself you can also use .Net’s code access security features to extend this authorization step to disk files, Registry keys and other resources.

Asp.Net Page Life Cycle:

When a page request is sent to the Web server, whether through a submission or location change, the page is run through a series of events during its creation and disposal. The page is loaded for the first time and has several server-side Web controls on it. When the Web server receives a request for the page, it will process our Web controls and we will eventually get rendered HTML. The first step in processing our page is object initialization.
1. Initialization() –oninit()  :   Controls are initialized based on their declaration as in the constructor but with no properties or attributes. So it is dangerous to access them through code
2. LoadViewState() : At the end of this phase, the ViewState property of a control is automatically populated. At LoadViewState event, the initialized controls receive their first properties: viewstate information that was persisted back to the server on the last submission
3. LoadPostData() : Loading ……Now the Server process incoming form data and update properties accordingly.  During this phase of the page creation, form data that was posted to the server is processed against each control that requires it.ie updates the control state with the correct postback data.Loaded…….
4. Load ()– OnLoad():  At this point, all controls in the server are updated with client control’s data Objects can be referenced easily through code or relative position.
5. RaisePostDataChanged(): Send postback change notifications
The RaisePostDataChanged event does not fire until all controls are updated and after the Load event has occurred. This ensures data in another control is not manually altered during the RaisePostDataChanged event before it is updated with postback data

6. RaisePostBackEvent Handle postback events.

Handle the client-side event that caused the postback and raise appropriate events on the server

7. PreRender – onPreRender()

The point at which the objects are prerendered is the last time changes to the objects can be saved or persisted to viewstate. This makes the PreRender step a good place to make final modifications, such as changing properties of controls or changing Control Tree structure, without having to worry about ASP.NET making changes to objects based off of database calls or viewstate updates. After the PreRender phase those changes to objects are locked in and can no longer be saved to the page viewstate. The PreRender step can be overridden using OnPreRender
8. ViewState Saved: The viewstate is saved after all changes to the page objects have occurred. Object state data is persisted in the hidden object and this is also where object state data is prepared to be rendered to HTML. At the SaveViewState event, values can be saved to the ViewState object, but changes to page controls are not
9. Render to HTML: The Render event commences the building of the page by assembling the HTML for output to the browser. During the Render event, the page calls on the objects to render them into HTML. The page then collects the HTML for delivery. When the Render event is overridden, the developer can write custom HTML to the browser that nullifies all the HTML the page has created thus far. The Render method takes an HtmlTextWriter object as a parameter and uses that to output HTML to be streamed to the browser. Changes can still be made at this point, but they are reflected to the client only.

1. Object Initialization:

A page’s controls (and the page itself) are first initialized in their raw form. By declaring your objects within the constructor of your C# code-behind file (see Figure 1), the page knows what types of objects and how many to create. Once you have declared your objects within your constructor, you may then access them from any sub class, method, event, or property. However, if any of your objects are controls specified within your ASPX file, at this point the controls have no attributes or properties. It is dangerous to access them through code, as there is no guarantee of what order the control instances will be created (if they are created at all). The initialization event can be overridden using the OnInit method.

2. Load Viewstate Data:

After the Init event, controls can be referenced using their IDs only (no DOM is established yet for relative references). At LoadViewState event, the initialized controls receive their first properties: viewstate information that was persisted back to the server on the last submission. The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden control that is passed from page request to page request. As you can see, this is a giant leap forward from the old ASP 3.0 techniques of maintaining state. This event can be overridden using the LoadViewState method and is commonly used to customize the data received by the control at the time it is populated.
3. LoadPostData()  - Processes Postback Data
Now the Server process incoming form data and update properties accordingly.
During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. When a page submits a form, the framework will implement the IPostBackDataHandler interface on each control that submitted data. The page then fires the LoadPostData event and parses through the page to find each control that implements this interface and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control’s unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page. Extra steps are taken by the framework to ensure each ID is unique in situations, such as several custom user controls existing on a single page.  After the LoadPostData event triggers, the RaisePostDataChanged event is free to execute.

4. Object Load

Objects take true form during the Load event. All objects are first arranged in the page DOM (called the Control Tree in ASP.NET) and can be referenced easily through code or relative position (crawling the DOM). Objects are then free to retrieve the client-side properties set in the HTML, such as width, value, or visibility. During Load, coded logic, such as arithmetic, setting control properties programmatically, and using the StringBuilder to assemble a string for output, is also executed. This stage is where the majority of work happens. The Load event can be overridden by calling OnLoad.

5. Raise PostBack Change Events

After updating controls with the correct postback data.,this event is raised. As stated earlier, this occurs after all controls that implement the IPostBackDataHandler interface have been updated with the correct postback data. During this operation, each control is flagged with a Boolean on whether its data was actually changed or remains the same since the previous submit. ASP.NET then sweeps through the page looking for flags indicating that any object’s data has been updated and fires RaisePostDataChanged. The RaisePostDataChanged event does not fire until all controls are updated and after the Load event has occurred. This ensures data in another control is not manually altered during the RaisePostDataChanged event before it is updated with postback data.

6. Process Client-Side PostBack Event

After the server-side events fire on data that was changed due to postback updates, the object which caused the postback is handled at the RaisePostBackEvent event. The offending object is usually a control that posted the page back to the server due to a state change (with autopostback enabled) or a form submit button that was clicked. There is often code that will execute in this event, as this is an ideal location to handle event-driven logic. The RaisePostBackEvent event fires last in the series of postback events due to the accuracy of the data that is rendered to the browser.
Controls that are changed during postback should not be updated after the executing function is called due to the consistency factor. That is, data that is changed by an anticipated event should always be reflected in the resulting page.

7. Prerender the Objects

The point at which the objects are prerendered is the last time changes to the objects can be saved or persisted to viewstate. This makes the PreRender step a good place to make final modifications, such as changing properties of controls or changing Control Tree structure, without having to worry about ASP.NET making changes to objects based off of database calls or viewstate updates. After the PreRender phase those changes to objects are locked in and can no longer be saved to the page viewstate. The PreRender step can be overridden using OnPreRender.

8. ViewState Saved

The viewstate is saved after all changes to the page objects have occurred. Object state data is persisted in the hidden object and this is also where object state data is prepared to be rendered to HTML. At the SaveViewState event, values can be saved to the ViewState object, but changes to page controls are not.

9. Render to HTML

The Render event commences the building of the page by assembling the HTML for output to the browser. During the Render event, the page calls on the objects to render them into HTML. The page then collects the HTML for delivery. When the Render event is overridden, the developer can write custom HTML to the browser that nullifies all the HTML the page has created thus far. The Render method takes an HtmlTextWriter object as a parameter and uses that to output HTML to be streamed to the browser. Changes can still be made at this point, but they are reflected to the client only.

10. Disposal

After the page’s HTML is rendered, the objects are disposed of. During the Dispose event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object.

jQuery with ASP.NET

JQuery is a light weight JavaScript library which that simplifies the way of HTML DOM traversing and manipulation, event handling, client side animations, etc. One of the greatest features of jQuery is, it supports an efficient way to implement AJAX applications because of its light weight nature. A few of its characteristics are light-weight, cross-browser compatibility and simplicity. The jQuery code we write is compatible with all the browsers and hence it prevents the need to write separate client side code for different browsers.
It provides Write less but do more concept.
Ex.
To select a HTML element in javascript,
document.getElementById('txtName');
The above equivalent in jQuery will be,
$('#txtName');
 

Sample Program: Hello World!

Display “Hello World” using jQuery.
1.      Create a Website File>New>WebSite>Choose ‘ASP.NET 3.5 website’ from the templates>Choose Location and Give name to your website.
2.      Now drag and drop the jquery-1.1.1.js file from the Solution Explorer’s >Script Folder on to your page to create a reference as shown below.
jQuery with ASP.NET
3.      Now, add a Button control to your page.
4.      Now, in .aspx file add this block of code to tell your browser to perform some task when page is loaded.
<script type="text/javascript">
        $(document).ready(function() {
        // add code here
        });
</script> 
 
 
5.      Now, Add your Code in this block to Display “Hello World !” using alert. Following are the codes:
<script type="text/javascript">
        $(document).ready(function () {
            $("#Button1").click(function () {
                alert("Hello world!");
            });
 
        });
    </script>
 
 
6.      Run the Website and Click on Button, you will see the following window:
jQuery with ASP.NET
 

Creating another Sample in ASP.NET using jQuery:

Here I have another example of jQuery with ASP.NET which will show some advance concept of jQuery.
Here, in this example I have used a GridView and inserted a CheckBox at the initial of every row and also I have added a CheckBox in Header of the GridView to make the GridView enable to Select or Deselect the all the CheckBoxes of the GridView at a time.
Start with Creating a GUI: Create a GUI as Follows.
jQuery with ASP.NET
Bind the Columns of the table using TemplateField. Here I named the page “Default.aspx”
Following is the Complete JavaScript code to make it functional to Select/Deselect all the CheckBoxes
<script type="text/javascript">
 
        //this function will tell browser to do something as soon as page is loaded
        $(document).ready(function () {
 
            //$("#<%=GridViewShowRecords.ClientID%> will get ther reference og GridView
            $("#<%=GridViewShowRecords.ClientID%> input[id*='chkEmployee']:checkbox").click(CheckUncheckAllCheckBoxAsNeeded);
            $("#<%=GridViewShowRecords.ClientID%> input[id*='chkAll']:checkbox").click(
            function () {
 
                //.is() method is used to find the state of the current checkbox, by querying its checked property.
                if ($(this).is(':checked'))
                    //setting the Checked Status of CheckBox to True
                    $("#<%=GridViewShowRecords.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', true);
                else
                    //setting the Checked Status of CheckBox to False
                    $("#<%=GridViewShowRecords.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', false);
            });
        });
 
        function CheckUncheckAllCheckBoxAsNeeded()
        {
            //this will count and store the no. of CheckBoes with id='chkEmployee'
            var totalCheckboxes = $("#<%=GridViewShowRecords.ClientID%> input[id*='chkEmployee']:checkbox").size();
            var checkedCheckboxes = $("#<%=GridViewShowRecords.ClientID%> input[id*='chkEmployee']:checkbox:checked").size();
 
            if (totalCheckboxes == checkedCheckboxes)
             {
                $("#<%=GridViewShowRecords.ClientID%> input[id*='chkAll']:checkbox").attr('checked', true);
            }
            else
             {
                $("#<%=GridViewShowRecords.ClientID%> input[id*='chkAll']:checkbox").attr('checked', false);
            }
        }
    </script>
 
Don’t forget to add the reference.( drag and drop the jquery-1.1.1.js file from the Solution Explorer’s >Script Folder on to your page to create a reference ).

Code for Default.aspx file

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShowRecords.aspx.cs" Inherits="ShowRecords"
    Debug="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>List of All Records</title>
    <%--This will add a reference for using jQuery--%>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        //this function will tell browser to do something as soon as page is loaded
        $(document).ready(function () {
            //$("#<%=GridViewShowRecords.ClientID%> will get ther reference og GridView
            $("#<%=GridViewShowRecords.ClientID%> input[id*='chkEmployee']:checkbox").click(CheckUncheckAllCheckBoxAsNeeded);
            $("#<%=GridViewShowRecords.ClientID%> input[id*='chkAll']:checkbox").click(
            function () {
 
                //.is() method is used to find the state of the current checkbox, by querying its checked property.
                if ($(this).is(':checked'))
                    //setting the Checked Status of CheckBox to True
                    $("#<%=GridViewShowRecords.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', true);
                else
                    //setting the Checked Status of CheckBox to False
                    $("#<%=GridViewShowRecords.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', false);
            });
        });
 
        function CheckUncheckAllCheckBoxAsNeeded()
        {
            //this will count and store the no. of CheckBoes with id='chkEmployee'
            var totalCheckboxes = $("#<%=GridViewShowRecords.ClientID%> input[id*='chkEmployee']:checkbox").size();
            var checkedCheckboxes = $("#<%=GridViewShowRecords.ClientID%> input[id*='chkEmployee']:checkbox:checked").size();
 
            if (totalCheckboxes == checkedCheckboxes)
             {
                $("#<%=GridViewShowRecords.ClientID%> input[id*='chkAll']:checkbox").attr('checked', true);
            }
            else
             {
                $("#<%=GridViewShowRecords.ClientID%> input[id*='chkAll']:checkbox").attr('checked', false);
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="margin: 0 auto;" width="1100px">
        <table style="margin: 0 auto;" width="1100px">
            <tr>
                <td>
                    <asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Names="Georgia" Text="Check all CheckBoxes in GridView using jQuery"></asp:Label>
                </td>
            </tr>
            <tr>
                <td bgcolor="#6699FF" align="center">
                    &nbsp;
                    <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Names="Georgia" ForeColor="White"
                        Text="List of All Records"></asp:Label>
                </td>
            </tr>
            <tr>
                <td align="center">
                    <asp:GridView ID="GridViewShowRecords" runat="server" BackColor="White" BorderColor="#DEDFDE"
                        BorderStyle="None" BorderWidth="1px" CellPadding="4" EnableModelValidation="True"
                        ForeColor="Black" GridLines="Vertical" AutoGenerateColumns="false">
                        <AlternatingRowStyle BackColor="White" />
                        <FooterStyle BackColor="#CCCC99" />
                        <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
                        <RowStyle BackColor="#F7F7DE" />
                        <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
                        <Columns>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    <asp:CheckBox runat="server" ID="chkAll" />
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:CheckBox runat="server" ID="chkEmployee" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    ID</HeaderTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblUserID" runat="server" Text='<%#Bind("UserId") %>'></asp:Label>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtUserID" Text='<%#Bind("UserId") %>' runat="server" Width="20px"
                                        Enabled="False"></asp:TextBox>
                                </EditItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    FirstName</HeaderTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblFirstName" runat="server" Text='<%#Bind("FName") %>'></asp:Label>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtFirstName" Text='<%#Bind("FName") %>' runat="server" Width="80px"></asp:TextBox>
                                </EditItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    LastName</HeaderTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblLastName" runat="server" Text='<%#Bind("LName") %>'></asp:Label>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtLastName" Text='<%#Bind("LName") %>' runat="server" Width="80px"></asp:TextBox>
                                </EditItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    FatherName</HeaderTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblFatherName" runat="server" Text='<%#Bind("FatherName") %>'></asp:Label>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtFatherName" Text='<%#Bind("FatherName") %>' runat="server" Width="100px"></asp:TextBox>
                                </EditItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    Age</HeaderTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblAge" runat="server" Text='<%#Bind("Age") %>'></asp:Label>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtAge" Text='<%#Bind("Age") %>' runat="server" Width="30px"></asp:TextBox>
                                </EditItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    Address</HeaderTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblAddress" runat="server" Text='<%#Bind("Address") %>'></asp:Label>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtAddress" Text='<%#Bind("Address") %>' runat="server" Width="150px"></asp:TextBox>
                                </EditItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    Phone</HeaderTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblPhone" runat="server" Text='<%#Bind("Phone") %>'></asp:Label>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtPhone" Text='<%#Bind("Phone") %>' runat="server" Width="80px"></asp:TextBox>
                                </EditItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    Email</HeaderTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblEmail" runat="server" Text='<%#Bind("Email") %>'></asp:Label>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtEmail" Text='<%#Bind("Email") %>' runat="server" Width="120px"></asp:TextBox>
                                </EditItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td>
                    <hr style="border-color: #6699FF" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>
 
Don’t have much more to code on Default.aspx.cs file. Simple you to do is Create your Connection to SQL SERVER and Bind the DataSource to GridView.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data; 
using System.Data.SqlClient;
using System.IO;
public partial class ShowRecords : System.Web.UI.Page
{  
  
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Binding the GridView
            BindGridViewShowRecords();
        }
    }
    private void BindGridViewShowRecords()
    {
        //Creating Connection and Binding the GridView
        connection.con = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
        connection.con.Open();
        string query = "select * from tblUserInfo";       
        connection.da = new System.Data.SqlClient.SqlDataAdapter(query, connection.con);
        connection.bui = new SqlCommandBuilder(connection.da);
        connection.dt = new System.Data.DataTable();
        connection.da.Fill(connection.dt);
        GridViewShowRecords.DataSource = connection.dt;
        GridViewShowRecords.DataBind();
    }
}
 
 
If you will click on Header CheckBox, it will select/deselect all checkboxes of the GridView.