Thursday 28 March 2013

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

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


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>
NameDescription
AllowPagingGets or sets a value indicating whether the paging feature is enabled.
autogeneratecolumnsGets or sets a value indicating whether bound fields are automatically created for each field in the data source.
emptydatatextGets 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.
DataKeyNamesGets or sets an array that contains the names of the primary key fields for the items displayed in a GridView control.
BoundFieldDisplays the value of a field in a data source. This is the default column type of the GridView control.
BoundField -> DataFieldGets or sets the name of the data field to bind to the BoundField object.
BoundField -> HeaderTextGets or sets the text that is displayed in the header of a data control
BoundField -> DataFormatStringGets or sets the string that specifies the display format for the value of the field.
ItemStyleGets 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

No comments:

Post a Comment