Saturday, 30 July 2011

Applying Template to GridView

The scope of this article was to create columns of check box in a GridView control. This GridView was created inside Repeater control. Please see the screen shot below.



Integration:
This article covers:
1. Creation of Template
2. Apply Template to GridView

Inner Working:
To add check box column to GridView we need to create template and apply it to column of GridView. Template created for GridView is:


        public class GridViewTemplate : ITemplate
        {

            //A variable to hold the type of ListItemType.
            ListItemType _templateType;

            //A variable to hold the column name.
            string _columnName;

            //Constructor where we define the template type and column name.
            public GridViewTemplate(ListItemType type, string colname)
            {
                _templateType = type;  //Stores the template type.
                _columnName = colname; //Stores the column name.
            }


            void ITemplate.InstantiateIn(System.Web.UI.Control container)
            {
                switch (_templateType)
                {

                    case ListItemType.Header:
                        //Creates a new label control and add it to the container.

                        Label lbl = new Label(); //Allocates the new label object.
                        lbl.Text = _columnName; //Assigns the name of the column in the lable.
                        //Adds the newly created label control to the container.
                        container.Controls.Add(lbl); 
                        break;

                    case ListItemType.Item:
                        if (_columnName == m_sFareColumn || _columnName == m_sClassDate)
                        {
                            Label lblColValue = new Label();
                            lblColValue.DataBinding += new EventHandler(lblCols_DataBinding);
                            container.Controls.Add(lblColValue);
                        }
                        else
                        {
                            //Creates a new text box control and add it to the container.
                            CheckBox chkBox = new CheckBox();
                            chkBox.ID = Guid.NewGuid().ToString();
                            chkBox.ClientIDMode = ClientIDMode.Static;

                             //Attaches the data binding event.
                            chkBox.DataBinding += new EventHandler(chkBox_DataBinding);   

                            //Adds the newly created textbox to the container.                                       
                            container.Controls.Add(chkBox);
                        }
                        break;

                }

            }

            /// <summary>
            /// Function lblCols_DataBinding() will apply text to Class and Fare column label
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void lblCols_DataBinding(object sender, EventArgs e)
            {
                Label lblColValue = (Label)sender;
                GridViewRow container = (GridViewRow)lblColValue.NamingContainer;
                object dataValue = DataBinder.Eval(container.DataItem, _columnName);

                if (dataValue != DBNull.Value)
                {
                    lblColValue.Text = dataValue.ToString();
                }
            }

            /// <summary>
            /// Function chkBox_DataBinding() will apply text to check box
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void chkBox_DataBinding(object sender, EventArgs e)
            {
                CheckBox chkBox = (CheckBox)sender;
                GridViewRow container = (GridViewRow)chkBox.NamingContainer;
                object dataValue = DataBinder.Eval(container.DataItem, _columnName);

                //Access Row values of GridView
                string Trainclass = ((System.Data.DataRowView)(container.DataItem)).Row.ItemArray[0].ToString();
                string Trainfare = ((System.Data.DataRowView)(container.DataItem)).Row.ItemArray[7].ToString();

                //Add client side event on click of check box 
                chkBox.Attributes.Add("onclick", "GetTrainSelection('" + _columnName +
                    "','" + dataValue.ToString() + "','" + Trainclass + "','" + Trainfare + "');");

                //Set colour of text in check box based on values present inside it
                if (dataValue != DBNull.Value)
                {
                    chkBox.Text = dataValue.ToString();
                    if (dataValue.ToString().Contains("AVAILABLE"))
                        chkBox.ForeColor = System.Drawing.Color.Green;
                    else if (dataValue.ToString().Contains("RAC"))
                        chkBox.ForeColor = System.Drawing.Color.Red;
                    else if (dataValue.ToString().Contains("TRAIN CANCELLED"))
                        chkBox.Enabled = false;
                    else if (dataValue.ToString().Contains("NOT AVAILABL"))
                        chkBox.Enabled = false;
                }

            }

        }

        #endregion

Apply template to GridVeiw.


         /// <summary>
        /// FillUPGridView() function will fill a gridview dynamically for given train ID
        /// </summary>
        /// <param name="strTrianNo">Train number whose train details are going to get displayed</param>
        /// <param name="gv_test">GridView that needs to be filled</param>
        protected void FillUPGridView(string strTrianNo, GridView gv_test)
        {
            try
            {
                gv_test.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
                gv_test.HeaderStyle.ForeColor = System.Drawing.Color.Black;

                DataTable dtTrain = new DataTable();
                //Fill up dataTable with required value
                dtTrain = GetTrainDetails(strTrianNo);

                foreach (DataColumn col in dtTrain.Columns)
                {
                    //Declare the bound field and allocate memory for the bound field.
                    TemplateField bfield = new TemplateField();

                    //Initalize the DataField value.
                    bfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);

                    //Initialize the HeaderText field value.
                    bfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName);

                    //Add the newly created bound field to the GridView.
                    gv_test.Columns.Add(bfield);

                }
                //Initialize the DataSource
                gv_test.DataSource = dtTrain;

                //Bind the datatable with the GridView.
                gv_test.DataBind();
            }
            catch
            {

            }
        }