CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Skip Navigation LinksHome » Article » ASP.Net Article » Create Dynamic GridView Control in C#/ASP.Net   You are not logged in.
Search
 

Technologies
 

Sponsors
 

CodeDigest Navigation
 

Technology News
 

Community News
No News Feeds available at this time.
 
Create Dynamic GridView Control in C#/ASP.Net

By Satheesh babu
Posted On Nov 19,2008
Article Rating: (Login)
Average Rating: 5
No of Ratings: 4
No of Comments: 20
Print this article.
Category: ASP.Net 2.0/3.5

Subscribe to our feed!

Create Dynamic GridView Control in C#/ASP.Net

 

Introduction

In my previous article, we have seen how to Create Dynamic DataList control in C#/ASP.Net.

 

Moving forward, we will see the implementation of dynamic GridView in this article.

Note

This article is continuation of my previous article Create Dynamic DataList control in C#/ASP.Net. I suggest you to read that article to have clear understanding of this article.

We will use the same example which we used to build dynamic datalist control in my previous article.

 

Implementing Dynamic GridView Control

Using the gridview to display the articles will display the article slightly in different layout when compared to DataList. Refer the below figure, Dynamic GridView.

Dynamic GridView

 

Constructing Dynamic GridView

Displaying the articles in gridview will be different from displaying in datalist. For achieving this, i have created two Template classes,

Ø       DynamicGridViewTextTemplate

Ø       DynamicGridViewURLTemplate.

 

DynamicGridViewTextTemplate class is used to add a template column with label while DynamicGridViewURLTemplate class is used to add URL of the article.

 

TemplateClass for GridView

public class DynamicGridViewTextTemplate : ITemplate

{

    string _ColName;

    DataControlRowType _rowType;

    int _Count;

    public DynamicGridViewTextTemplate(string ColName, DataControlRowType RowType)

    {

        _ColName = ColName;

        _rowType = RowType;

    }

    public DynamicGridViewTextTemplate(DataControlRowType RowType, int ArticleCount)

    {

        _rowType = RowType;

        _Count = ArticleCount;

    }

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

    {

        switch (_rowType)

        {

            case DataControlRowType.Header:

                Literal lc = new Literal();

                lc.Text = "<b>" + _ColName + "</b>";

                container.Controls.Add(lc);

                break;

            case DataControlRowType.DataRow:              

                 Label lbl = new Label();

                 lbl.DataBinding += new EventHandler(this.lbl_DataBind);

                 container.Controls.Add(lbl);              

                break;

            case DataControlRowType.Footer:

                Literal flc = new Literal();

                flc.Text = "<b>Total No of Articles:" + _Count + "</b>";

                container.Controls.Add(flc);

                break;

            default:

                break;

        }

    }

 

  

    private void lbl_DataBind(Object sender, EventArgs e)

    {

        Label lbl  = (Label)sender;

        GridViewRow row = (GridViewRow)lbl.NamingContainer;

        lbl.Text =DataBinder.Eval(row.DataItem, _ColName).ToString();

    }

 

}

public class DynamicGridViewURLTemplate : ITemplate

{

    string _ColNameText;

    string _ColNameURL;

    DataControlRowType _rowType;

 

    public DynamicGridViewURLTemplate(string ColNameText, string ColNameURL, DataControlRowType RowType)

    {

        _ColNameText = ColNameText;

        _rowType = RowType;

        _ColNameURL = ColNameURL;

    }

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

    {

        switch (_rowType)

        {

            case DataControlRowType.Header:

                Literal lc = new Literal();

                lc.Text = "<b>" + _ColNameURL + "</b>";

                container.Controls.Add(lc);

                break;

            case DataControlRowType.DataRow:

                HyperLink hpl = new HyperLink();

                hpl.Target = "_blank";

                hpl.DataBinding += new EventHandler(this.hpl_DataBind);

                container.Controls.Add(hpl);

                break;

            default:

                break;

        }

    }

 

    private void hpl_DataBind(Object sender, EventArgs e)

    {

        HyperLink hpl = (HyperLink)sender;

        GridViewRow row = (GridViewRow)hpl.NamingContainer;

        hpl.NavigateUrl = DataBinder.Eval(row.DataItem, _ColNameURL).ToString();

        hpl.Text = "<div class=\"Post\"><div class=\"PostTitle\">" + DataBinder.Eval(row.DataItem, _ColNameText).ToString() + "</div></div>";

    }

}

 



ASP.Net Hosting

Recent Articles

Using the Template Class in GridView

Using dynamic template in gridview is slightly different from datalist i.e. we will create the dynamic gridview in column wise with header template, item template and footer template from the first column till the last.

Steps:

1.      Create a Gridview Object.

2.      Create an instance of TemplateField object.

3.      Instantiate the Dynamic template class with proper ListItemType and assign it to corresponding template property of TemplateField object and finally add this object to the column collection of GridView. Refer the below code for better understanding.

Templates of GridView

TemplateField tf = new TemplateField();

                tf.HeaderTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.Header);

                tf.ItemTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.DataRow);

                tf.FooterTemplate = new DynamicGridViewTextTemplate(DataControlRowType.Footer, ds.Tables[i].Rows.Count);            

 

If you compare the implementation of DataList, in Gridview we won’t create dynamic template for the grid instead we create it for the grid’s column (TemplateField). Refer the below code (Using Template class) for clear understanding.

Using Template class

for (int i = 0; i < ds.Tables.Count; i++)

        {

            if (ds.Tables[i].Rows.Count > 0)

            {

                GridView gvDynamicArticle = new GridView();

                gvDynamicArticle.Width = Unit.Pixel(700);

                gvDynamicArticle.BorderWidth = Unit.Pixel(0);

                gvDynamicArticle.Caption = "<div id=\"nifty\" class=\"PostCategory\"> + ds.Tables[i].Rows[0]["Category"].ToString() + " Articles</div>";

                gvDynamicArticle.AutoGenerateColumns = false;

                gvDynamicArticle.ShowFooter = true;

                TemplateField tf = null;

 

                tf = new TemplateField();

                tf.HeaderTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.Header);

                tf.ItemTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.DataRow);

                tf.FooterTemplate = new DynamicGridViewTextTemplate(DataControlRowType.Footer, ds.Tables[i].Rows.Count);               

              

                gvDynamicArticle.Columns.Add(tf);

 

                tf = new TemplateField();

                tf.HeaderTemplate = new DynamicGridViewTextTemplate("Title", DataControlRowType.Header);

                tf.ItemTemplate = new DynamicGridViewTextTemplate("Title", DataControlRowType.DataRow);

                gvDynamicArticle.Columns.Add(tf);

 

                tf = new TemplateField();

                tf.HeaderTemplate = new DynamicGridViewTextTemplate("Description", DataControlRowType.Header);

                tf.ItemTemplate = new DynamicGridViewTextTemplate("Description", DataControlRowType.DataRow);

                gvDynamicArticle.Columns.Add(tf);

 

                tf = new TemplateField();

                tf.HeaderTemplate = new DynamicGridViewURLTemplate("Title", "URL", DataControlRowType.Header);

                tf.ItemTemplate = new DynamicGridViewURLTemplate("Title", "URL", DataControlRowType.DataRow);

                gvDynamicArticle.Columns.Add(tf);

 

                tf = new TemplateField();

                tf.HeaderTemplate = new DynamicGridViewTextTemplate("Author", DataControlRowType.Header);

                tf.ItemTemplate = new DynamicGridViewTextTemplate("CreatedBy", DataControlRowType.DataRow);

                gvDynamicArticle.Columns.Add(tf);

 

 

                gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(this.DynamicGrid_RowDataBound);

 

                gvDynamicArticle.DataSource = ds.Tables[i];

                gvDynamicArticle.DataBind();

                phDynamicGridHolder.Controls.Add(gvDynamicArticle);

            }

        }

In the above code (Using Template class), we can clearly understand that we are creating the dynamic template for the gridview’s column as opposed to Datalist where we created the template for the grid itself. To throw more light on this it means that we are creating the first column’s header, item and footer and adding it to the gridview’s column list through TemplateField object till the last column as I said earlier.

Download the source with the article and see it in action.

Downloads:

Dynamic Gridview

 

References:

MSDN

 

Conclusion

The functionalities like displaying table of data on a public website like the one in our example or displaying report in a webpage in an enterprise application is one the major thing that we do in everyday development. This article will help you to do that dynamically with the help of GridView control in ASP.Net 2.0.

Enjoy Coding!!!

Similar Articles
  • You can contribute to CodeDigest.Com:
    Article Feedback
    Title  
    Submitted By  
    Comment  
    Enter the verification number
     
    Comments
    Dynamic GridView
    Good article,

    can u tell how to traverse these dynamic gridview.

    thanks
    Create Dynamic GridView Control in C#/ASP.Net
    Here If we want to generate a grid view with condition but value of condition is pass throw the control its possible
    update dynamic
    Doy you know how add an edit button dynamic?
    Dynamic GridView
    Excellent Article!!!!

    I was working this weekend but my problem was resolved with this information for generate gridviews dynamics.

    Best Regards.

    I dont know my job without Internet
    grid
    i am half gridview code from aspx and half code dynamically but space commin between them
    .Net Dev
    It a good Article and working for me....
    But I have a small trouble in it.actually I am binding a dataset to this grid. The thing is along with data set I am getting some null rows with it which I dont want to bind to a grid view. I tried to handle it in row data bound event but no use...

    can you help me out in this.


    Thanks in advance...
    Nice Article
    Its really working for me... Thanks a lot ....
    Excellenct
    Its really a nice..........thanks a lot.......
    Hi
    Thanks a lot for the code.
    Stuff
    fdsadc ajdfkda as a d akjdfafjak
    Adding row to gridview
    In my grid view getting data from database and grid view has textbox,listbox,dropdowlist and checkbox. Now user want to add some new record, Basically click on add button click it should add row to my gird view with the above controls they can select values and they can do again click add and do same thing and finally on the top I have save button so all the values they have enter will able to save.
    Is it possible and how in asp.net using c# ?
    s
    dfgjk
    good
    Worked out...good one.
    A little bit lack of description
    I tried to apply this code, but as I needed to customize it for my needs, I'm not able to understand everything (I'm not a pro developper atm, but got some good knowledge of asp.net c#).

    A bit more code description would be really useful :)

    V.
    Great Article
    Great Article, it saved me a lot of time. I was not sure where to start but this helped out greatly.
    Great Article
    Great Article save me a lot of time. I was not where to start but this helped out greatly.
    Dynamic Gridview-Ajax
    How to apply ajax on paging so that postback doesnt happen
    RE:bad download link
    Apologies, the attachment is now updated. Thanks for informing me!
    bad download link
    the Dynamic Gridview link shown above points to the zip file for the DynamicDataList code (168.zip)

    rob k
    retrive the data from dymanic grid and add a new row
    hi, nice article :)

    maybe you can help me with a problem i have.
    i have a dynamic gridview and at the footer a botton to add a new row do the grid. since the grid is always in edit mode when creating a new row i need to retrieve the data from the grid and then create the row to insure that none of the data will be lost.

    since, i've been unable to find a way to retrive the datasource from the grid, i've implemented a method to iterate to all rows at grid and retrive information that i need. and that works, but now that i have a dynamic grid that just doesn't work.

    could you give me some advise of a better way to do this?

    tks in advance

    Aga