• Using GridView in ASP.NET & C# — PART 1

    Posted on March 28, 2012 by in ASP.NET, C#, Dotnet

    GridView displays the values of a data source in a table where each column represents a field and each row represents a record. The GridView control enables you to select, sort, and edit these items. In this article I would discuss some basic scenarios using GridView.

    Example 1: Bind the Gridview with DataSet

    Step 1: Create a new ASP.NET Web Application in Visual Studio

    Step 2: I am using AdventureWorks for my samples. Open web.config and add following entry to connection strings element

    <add name="Sql" connectionString="Data Source=<SERVERNAME>;
         Initial Catalog= AdventureWorks;User=testuser;Password=testuser;" 
         providerName="System.Data.SqlClient"/> 

     

    Step 3: Open aspx file in design mode and add the following in div tag

    <asp:gridview id="gvProducts"          
              autogeneratecolumns="False"
              emptydatatext="No data available."           
              runat="server" DataKeyNames="ProductID">
       <Columns>
         <asp:BoundField DataField="ProductID" HeaderText="Product ID"/>
         <asp:BoundField DataField="Name" HeaderText="Product Name" />         
         <asp:BoundField DataField="ProductNumber" HeaderText="Product Number" />    
         <asp:BoundField HeaderText="Price" 
                      DataField="ListPrice"
                      DataFormatString="{0:c}">
              <ItemStyle HorizontalAlign="Right"></ItemStyle>
         </asp:BoundField>                 
       </Columns>
    </asp:gridview>
    Name Description
    AllowPaging Gets or sets a value indicating whether the paging feature is enabled.
    autogeneratecolumns Gets or sets a value indicating whether bound fields are automatically created for each field in the data source.
    emptydatatext Gets or sets the text to display in the empty data row rendered when a GridView control is bound to a data source that does not contain any records.
    DataKeyNames Gets or sets an array that contains the names of the primary key fields for the items displayed in a GridView control.
    BoundField Displays the value of a field in a data source. This is the default column type of the GridView control.
    BoundField -> DataField Gets or sets the name of the data field to bind to the BoundField object.
    BoundField -> HeaderText Gets or sets the text that is displayed in the header of a data control
    BoundField -> DataFormatString Gets or sets the string that specifies the display format for the value of the field.
    ItemStyle Gets the style of any text-based content displayed by a data control field.

    Step 4: Open Default.aspx.cs and add the following code in the page_load function

    //fetch the connection string from web.config
    string connString = ConfigurationManager.ConnectionStrings["Sql"].ConnectionString;
    
    //SQL statement to fetch 10 entries from product category
    string sql = @"Select top 10  P.ProductID, P.Name, 
                P.ProductNumber, ListPrice from Production.Product P
                where ProductSubcategoryID is not null";
    
    DataSet dsResults = new DataSet();
    //Open SQL Connection
    using (SqlConnection conn = new SqlConnection(connString)) 
    { 
        conn.Open(); 
        //Initialize command object
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            //Fill the result set
            adapter.Fill(dsResults);
        }
    }
    //Bind the grid view
    gvProducts.DataSource = dsResults;
    gvProducts.DataBind();

     

    Step 5: Run the application

    Output:

    Example 2: Bind the GridView with SQL DataReader

    Step 1: Repeat Steps 1 to Step 3 from “Bind the Gridview with DataSet” section

    Step 2: Open Default.aspx.cs and add the following code in the page_load function

    //fetch the connection string from web.config
    string connString = ConfigurationManager.ConnectionStrings["Sql"].ConnectionString;
    //SQL statement to fetch 10 entries from product category
    string sql = @"Select top 10  P.ProductID, P.Name, 
                P.ProductNumber, ListPrice from Production.Product P
                where ProductSubcategoryID is not null";
    SqlDataReader reader = null;
    //Open SQL Connection
    using (SqlConnection conn = new SqlConnection(connString)) 
    { 
        conn.Open(); 
        //Initialize command object
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            reader = cmd.ExecuteReader();        
            //Bind the grid view
            gvProducts.DataSource = reader;
            gvProducts.DataBind();    }
    }

     

    Step 3: Run the application.

    Output

    Be Sociable, Share!
      Post Tagged with , ,

    Written by

    Software architect with over 10 years of proven experience in designing & developing n-tier and web based software applications, for Finance, Telecommunication, Manufacturing, Internet and other Commercial industries. He believes that success depends on one's ability to integrate multiple technologies to solve a simple as well as complicated problem.

    View all articles by

    Email : [email protected]

    2 Responsesso far.

    1. HelpfulGuy says:

      Good article, but like everybody who posts, neglects the required using statements:

      using System.Data;
      using System.Data.SqlClient;
      using System.Configuration;

    2. sudhakar says:

      good article keep it up your giving life to more number of begginers

    Leave a Reply