Sunday, July 31, 2011

Creating Dynamically GridView with custom Template Field in C#

GridView – big brother of data grid, one of the mostly used controls for its effective use of representing data. Smile Ok ok, let us get to the topic now, to start with ……………...

TemplateField Class

This example shows how to create a GridView dynamically and add desired columns. I have used this in asp.net page and I had to add the GridView in the aspx page, rest all in the code behind file.  Before starting did some R&D and found some information on the available Column Fields from in MSDN and thought to share a bit of it here.

 

Column Fields

Each column in the GridView control is represented by a DataControlField object. By default, the AutoGenerateColumns property is set to true, which creates an AutoGeneratedField object for each field in the data source. Each field is then rendered as a column in the GridView control in the order that each field appears in the data source.

You can also manually control which column fields appear in the GridView control by setting the AutoGenerateColumns property to false and then defining your own column field collection. Different column field types determine the behavior of the columns in the control. The following table lists the different column field types that can be used.

Column field type

Description

BoundField

Displays the value of a field in a data source. This is the default column type of the GridView control.

ButtonField

Displays a command button for each item in the GridView control. This enables you to create a column of custom button controls, such as the Add or the Remove button.

CheckBoxField

Displays a check box for each item in the GridView control. This column field type is commonly used to display fields with a Boolean value.

CommandField

Displays predefined command buttons to perform select, edit, or delete operations.

HyperLinkField

Displays the value of a field in a data source as a hyperlink. This column field type enables you to bind a second field to the hyperlink's URL.

ImageField

Displays an image for each item in the GridView control.

TemplateField

Displays user-defined content for each item in the GridView control according to a specified template. This column field type enables you to create a custom column field.

 

To define a column field collection declaratively, first add opening and closing <Columns> tags between the opening and closing tags of the GridView control. Next, list the column fields that you want to include between the opening and closing <Columns> tags. The columns specified are added to the Columns collection in the order listed. The Columns collection stores all the column fields in the control and enables you to programmatically manage the column fields in the GridView control.

 

Explicitly declared column fields can be displayed in combination with automatically generated column fields. When both are used, explicitly declared column fields are rendered first, followed by the automatically generated column fields.

Now, after all these information, I am sure now know what are the column types you can use in a GridView. In this article I will only deal with the Template Column and that too in code base.  In precise, it can be done by implementing ITemplate interface in System.Web.UI namespace. In this article, I will explain the construction of dynamic GridView  control by building dynamic template columns.

The Template class

public class MyGridViewTemplate : ITemplate

{

    private DataControlRowType templateType;

    private string columnName;

 

    public MyGridViewTemplate(DataControlRowType type, string colname)

    {

        templateType = type;

        columnName = colname;

    }

 

    public void InstantiateIn(System.Web.UI.Control container)

    {

        // Create the content for the different row types.

        switch (templateType)

        {

            case DataControlRowType.Header:

                // Create the controls to put in the header section and set their properties.

                Literal lc = new Literal();

                lc.Text = "<B>" + columnName + "</B>";

                // Add the controls to the Controls collection of the container.

                container.Controls.Add(lc);

                break;

            case DataControlRowType.DataRow:

                // Create the controls to put in a data row section and set their properties.

                Label firstName = new Label();

                Label lastName = new Label();

                Literal spacer = new Literal();

                spacer.Text = " ";

 

                // To support data binding, register the event-handling methods

                // to perform the data binding. Each control needs its own event handler.

                firstName.DataBinding += new EventHandler(this.FirstName_DataBinding);

                lastName.DataBinding += new EventHandler(this.LastName_DataBinding);

 

                // Add the controls to the Controls collection of the container.

                container.Controls.Add(firstName);

                container.Controls.Add(spacer);

                container.Controls.Add(lastName);

                break;

 

            // Insert cases to create the content for the other row types, if desired.

 

            default:

                // Insert code to handle unexpected values.

                break;

        }

    }

 

    private void FirstName_DataBinding(Object sender, EventArgs e)

    {

        // Get the Label control to bind the value. The Label control

        // is contained in the object that raised the DataBinding event (the sender parameter).

        Label l = (Label)sender;

 

        // Get the GridViewRow object that contains the Label control. 

        GridViewRow row = (GridViewRow)l.NamingContainer;

 

        // Get the field value from the GridViewRow object and assign it to the Text property of the Label control.

        l.Text = DataBinder.Eval(row.DataItem, "Links").ToString();

      

    }

 

    private void LastName_DataBinding(Object sender, EventArgs e)

    {

        // Get the Label control to bind the value. The Label control

        // is contained in the object that raised the DataBinding event (the sender parameter).

        Label l = (Label)sender;

 

        // Get the GridViewRow object that contains the Label control.

        GridViewRow row = (GridViewRow)l.NamingContainer;

 

        // Get the field value from the GridViewRow object and assign it to the Text property of the Label control.

        l.Text = DataBinder.Eval(row.DataItem, "Links1").ToString();

    }

}

 

And now we will see the page class. aspx.cs

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

{

    #region Controls  + Variables

    #endregion

 

    protected void Page_Load(object sender, EventArgs e)

    {

       

        ////Populate Data

        DataTable dt = new DataTable();

        dt.Columns.Add("Links");

        dt.Columns.Add("Links1");

        DataRow dr;

        for (int i = 1; i < 10; i++)

        {

            dr = dt.NewRow();

            dr["Links"] = "A" + i;

            dr["Links1"] = "B" + i;

            dt.Rows.Add(dr);

            dt.AcceptChanges();

        }

        ////Grid view

        // The field columns need to be created only when the page is first loaded. 

        if (!IsPostBack)

        {

            gvTest.AutoGenerateColumns = false;

            // Dynamically create field columns to display the desired

            // fields from the data source. Create a TemplateField object 

            // to display an author's first and last name.

            TemplateField customField = new TemplateField();

            // Create the dynamic templates and assign them to 

            // the appropriate template property.

            customField.HeaderTemplate = new MyGridViewTemplate(DataControlRowType.Header, "Test Name");

            customField.ItemTemplate = new MyGridViewTemplate(DataControlRowType.DataRow, "");

            // Add the field column to the Columns collection of the GridView control.

            this.gvTest.Columns.Add(customField);

 

            BoundField boundField = new BoundField();

            boundField.HeaderText = "Bug ID";

            boundField.DataField = "Links";

            this.gvTest.Columns.Add(boundField);

 

            gvTest.DataSource = dt;

            gvTest.DataBind();

           

        }

    }

}
Hope few simple copy paste and the code should run…. Smile


If you have a more elegant solution – please post a comment… I’ll be happy to hear.

...HaPpY CoDiNg

Partha (Aurum)

 

Creating Dynamically GridView  with custom Template Field in C#

 

TemplateField in GridView

Creating GridView in C# by Code

Implementing ITemplate for custom TemplateField in GridView

5 comments:

  1. I was able to construct entire grid using 5 diff versions of this!!
    thank you very much for such detailed explanation and nice coding standards as well!

    ReplyDelete
  2. yes Very Nice Description
    but can u show how to handle its gridediting or click event of gridview

    the problem is postback

    ReplyDelete
  3. hi, i want to add textboxes dynamically, how can i do this

    ReplyDelete
  4. Money they say is "material" but this "material" is certainly one thing that every human being on earth loves to have. Well we are often posed a question as to what is our favorite Trey Songz Net Worth red or black or white. In reality; what matters is the color green.

    ReplyDelete