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 :

1)FirstName

2)MiddleName

3)LastName

4)BirthDate

5)CustomerKey

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

</pre>
<form id="frmExmGrdView" runat="server">
    <asp:GridView ID="grd" runat="server" CssClass="gdview" HeaderStyle-CssClass="hd" AutoGenerateColumns="false" BorderStyle="None">
    <Columns>
    <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>
    </Columns>
    </asp:GridView>
    </form>
<pre>

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);
        con.Open();
        SqlDataReader dtrClient = cmd.ExecuteReader();
        grd.DataSource = dtrClient;
        grd.DataBind();
        con.Close();
    }

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 ( https://mstechexplore.wordpress.com )

Advertisements