ASP.NET – How to work with GridView

Today we are going to see how to work with Grid View Control.

Here is an example how are we going to get a repeater after we finished coding.

Here I am using AdventureWorks in SQL SERVER which can be downloaded from codeplex.

The table I am using is DimCustomer and fields are :






Step 1 :  Add the control in the <body> tag in page in .aspx side let it be grdView.aspx

<form id="frmExmGrdView" runat="server">
    <asp:GridView ID="grd" runat="server" CssClass="gdview" HeaderStyle-CssClass="hd" AutoGenerateColumns="false" BorderStyle="None">
    <asp:BoundField DataField="FirstName" HeaderText="Login" ItemStyle-Width="40" ItemStyle-HorizontalAlign="Left" ></asp:BoundField>
    <asp:BoundField DataField="MiddleName" HeaderText="Initial" ItemStyle-Width="20" ItemStyle-HorizontalAlign="Left" ></asp:BoundField>
    <asp:BoundField DataField="LastName" HeaderText="Name" ItemStyle-Width="60" ItemStyle-HorizontalAlign="Left" ></asp:BoundField>
    <asp:BoundField DataField="BirthDate" HeaderText="DateAdded" ItemStyle-Width="40" ItemStyle-HorizontalAlign="Left" HtmlEncode="false" DataFormatString={0:d}></asp:BoundField>

NOTE: Dont forget to make the form tag as runat = “server “

otherwise an error will occur because you are trying to insert the data from .cs

side but u can only access it when u make runat = “server “

STEP 2:  Now insert the data from the code behind (.cs side) in Page_Load event


protected void Page_Load(object sender, EventArgs e)
        SqlConnection con = new SqlConnection("Server=localhost;UID=sa;PWD=dilip;Database=AdventureWorksDW");
        string sSQL = "Select top 5 * from dbo.DimCustomer";
        SqlCommand cmd = new SqlCommand(sSQL, con);
        SqlDataReader dtrClient = cmd.ExecuteReader();
        grd.DataSource = dtrClient;

The last 2 lines binding the data to the repeater and starting remaining lines is to establish connection to database.

the output will come as shown above .

Reference : Dilip Kumar Jena ( )


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s