using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

using Utilities;

using System.Data;

 

namespace GridViews

{

    public partial class GridViewExample12b : System.Web.UI.Page

    {

        DBConnect objDB = new DBConnect();

        DataSet myDS;

 

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                String strSQL = "SELECT * FROM Product";

                myDS = objDB.GetDataSet(strSQL);

                gvProducts.DataSource = myDS;

 

                // Set the DataKeyNames collection to store the ProductNumber in a DataKeys collection.

                // This is needed when you want to use primary keys in columns of a GridView and hide those columns.

                // Hidden columns are not rendered into HTML making the unavailable through the Cells collection of a Rom.

                String[] names = new String[1];

                names[0] = "ProductNumber";

                gvProducts.DataKeyNames = names;

                gvProducts.DataBind();

            }

        }

 

        protected void gvProduct_RowCommand(Object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)

        {

            // Get the index of the row that a command was issued on

            int rowIndex = int.Parse(e.CommandArgument.ToString());

            //int rowIndex = Convert.ToInt32(e.CommandArgument);

 

            // Get the ProductNumber from the DataKeys colletion of the row

            // The values were previously stored in the DataKeys collection during the DataBind method

            // because the GridView control's property DataKeyNames="ProductNumber"

            String productNum = gvProducts.DataKeys[rowIndex].Value.ToString();

 

These IF statements use the GridViewCommandEventArgs object to determine which ButtonField was clicked by the event argument CommandName Property.

The value of CommandName Property of the object e corresponds to the value set in the ASPX markup for the ButtonField’s CommandName attribute.

 
            if (e.CommandName == "AddToCart")

                lblDisplay.Text = "The product (ProductNumber: " + productNum + ") was added to the cart.";

 

            else if (e.CommandName == "ProductReviews")

                lblDisplay.Text = "There are no reviews posted for this product (ProductNumber: " + productNum + ").";

 

            else

                lblDisplay.Text = "";

 

        }

    }

}