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

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

     

    In my previous article “Using GridView in ASP.NET & C# — PART 1”, I discussed about basic usage of grid view. In this article, I am going to go little further and discuss about more available grid columns and their properties.

    Example: GridView with Bound, Button & Template Column types

    Retrieve & display basic productions information from the database. When user selects a product, take them to a ProductDetail page and print the selected product ID.

    Step 1: Create a new ASP.NET Web Application project.

    Step 1a:  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 2: Create a new aspx page and name it as ProductsView.aspx. Open the aspx file in design mode and add the following code in div tag

    <asp:gridview id="gvProducts"          
              autogeneratecolumns="False"
              emptydatatext="No data available."           
              runat="server" DataKeyNames="ProductID"
              OnRowCommand="ProductsView_RowCommand">
        <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>
         <asp:templatefield headertext="Available">
               <itemtemplate>
                    <itemstyle HorizontalAlign="Center"/>
                    <asp:label id="FirstNameLabel" 
                            Text= '<%# IsAvailable(Eval("SellEndDate")) %>'
                            runat="server"/>                      
                    </itemtemplate>
         </asp:templatefield>
         <asp:buttonfield buttontype="Button" 
                          commandname="Select"
                          headertext="" 
                          text="Select"/>                                 
       </Columns>
      </asp:gridview>
    Name Description
    OnRowCommand=

          “ProductsView_RowCommand”

    Raises the RowCommand event. The RowCommand event is raised when a button is clicked in the GridView control. This enables you to provide an event-handling method that performs a custom routine whenever this event occurs.
    asp:BoundField Displays the value of a field in a data source.
    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.
    TemplateField The TemplateField class is used by data-bound controls (such as GridView) to display custom content for each record displayed. When you need to display content in a data-bound control that is not provided by one of the predefined data control fields (such as BoundField), use the TemplateField class to create your custom user interface (UI).
    TemplateField -> ItemTemplate Use the ItemTemplate property to specify the custom content displayed for the items in a TemplateField object. Define the content by creating a template that specifies how the items are rendered. 
    Eval(“SellEndDate”) Data-binding expressions are contained within <%# and=””> delimiters and use the Eval and Bind functions. The Eval function is used to define one-way (read-only) binding.

    Step 3: Open ProductsView.aspx.cs and add following methods 

    protected void Page_Load(object sender, EventArgs e)
    {
        //fetch the connection string from web.config
        string connString = 
                  ConfigurationManager.ConnectionStrings["Sql"].ConnectionString;
        //SQL statement to fetch entries from products
        string sql = @"Select top 20  P.ProductID, P.Name, 
                      P.ProductNumber, ListPrice, SellEndDate 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();
            }
        }
    }
    
    public void ProductsView_RowCommand(Object sender, 
    GridViewCommandEventArgs e)
    {
        // If multiple ButtonField column fields are used, use the
        // CommandName property to determine which button was clicked.
        if (e.CommandName == "Select")
        {
            // Convert the row index stored in the CommandArgument
            // property to an Integer.
            int index = Convert.ToInt32(e.CommandArgument);
            // Get the product id of the selected product                
            GridViewRow selectedRow = gvProducts.Rows[index];
            string ID = gvProducts.DataKeys[index].Value.ToString();         
            //Redirect the user to product detail view page
            Server.Transfer("ProductDetailView.aspx?ProductID=" + ID);
        }
    }
    
    /// <summary>
    /// function to check if product is discontinued. 
    /// if discontinued "N" is returned, else "Y" is returned
    /// </summary>       
    public string IsAvailable(object SellEndDate)
    {
        DateTime dateValue;
        string availableString = "Y";
        if (SellEndDate != null)
        {
       //check if the sellenddate is less than today’s date
            if (DateTime.TryParse(SellEndDate.ToString(), out dateValue))
            {
                if (DateTime.Now.Subtract(dateValue).TotalHours > 1)
                    availableString = "N";
            }                     
        }
        return availableString;
    }        
    

    Step 4:  Run the application and you would see following page

    Step 5: When you click on button “Select” button on any row. You would be redirected to ProductDetailView page.

    Step 6:  Create a new ASPX page. Rename it as ProductDetails.aspx.

    Step 7:  Open ProductDetails.aspx.cs and add the following code in page_load method

    protected void Page_Load(object sender, EventArgs e)
    {
       if (Request.QueryString["ProductID"] != null)
       {
            Response.Write("You have selected product: " + 
     Request.QueryString["ProductID"].ToString());
      }
    }
    
    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]

    One Responseso far.

    1. kooteswara says:

      super super god favours yours helping attitude

    Leave a Reply