locked
Dynamically creating TemplateField for GridView RRS feed

  • Question

  • User-1827408301 posted

    From code I need to dynamically create a column for a GridView.  This column must be databound and it must have a hyperlink.  If I were doing this from the ASPX source it is simple enough to create a TemplateColumn, but I am having difficulty doing it from code.

    So, irrespective of the type of column that is created, from code I need to dynamically create a column that is databound and has a hyperlink.  How can I do this?

    Thanks for your help.

    Chris

    Wednesday, June 21, 2006 4:40 PM

Answers

  • User-1950088788 posted

    Hi,

    I have given code for dynamically adding template column with hyperlink to GridView.

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>"
                SelectCommand="SELECT [au_id], [au_lname], [au_fname] FROM [authors]"></asp:SqlDataSource>
       
       
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="au_id"
                DataSourceID="SqlDataSource1">


     private void BuildTemplateColumnsDynamically()
        {
            BoundField fname = new BoundField();
            fname.DataField = "au_fname";
            fname.HeaderText = "Author FirstName";
            TemplateField lname = new TemplateField();
            lname.HeaderText = "Author LastName"; 
            lname.ItemTemplate = new AddTemplateToGridView(ListItemType.Item, "au_lname");
            GridView1.Columns.Add(lname);
            GridView1.Columns.Add(fname);
        }

        public class AddTemplateToGridView : ITemplate
        {
            ListItemType _type;
            string _colName;

            public AddTemplateToGridView(ListItemType type, string colname)
            {           
                _type = type;

               _colName = colname;

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

                switch (_type)
                {
                         case ListItemType.Item:                 

                             HyperLink ht = new HyperLink();
                             ht.Target = "_blank"; 
                             ht.DataBinding+=new EventHandler(ht_DataBinding);
                             container.Controls.Add(ht);                          

                         break;      
                }

            }

            void ht_DataBinding(object sender, EventArgs e)
            {

                HyperLink lnk = (HyperLink)sender;
                GridViewRow container = (GridViewRow)lnk.NamingContainer;
                object dataValue = DataBinder.Eval(container.DataItem, _colName);
                if (dataValue != DBNull.Value)
                {
                    lnk.Text = dataValue.ToString();
                    lnk.NavigateUrl = "http://www.booktitles.com";
                }

            }

     

    Thanks
    Sharmila
    (www.syncfusion.com)

    ASP.Net FAQ:
    http://www.syncfusion.com/faq/aspnet/default.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 22, 2006 7:57 AM

All replies

  • User-1950088788 posted

    Hi,

    I have given code for dynamically adding template column with hyperlink to GridView.

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>"
                SelectCommand="SELECT [au_id], [au_lname], [au_fname] FROM [authors]"></asp:SqlDataSource>
       
       
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="au_id"
                DataSourceID="SqlDataSource1">


     private void BuildTemplateColumnsDynamically()
        {
            BoundField fname = new BoundField();
            fname.DataField = "au_fname";
            fname.HeaderText = "Author FirstName";
            TemplateField lname = new TemplateField();
            lname.HeaderText = "Author LastName"; 
            lname.ItemTemplate = new AddTemplateToGridView(ListItemType.Item, "au_lname");
            GridView1.Columns.Add(lname);
            GridView1.Columns.Add(fname);
        }

        public class AddTemplateToGridView : ITemplate
        {
            ListItemType _type;
            string _colName;

            public AddTemplateToGridView(ListItemType type, string colname)
            {           
                _type = type;

               _colName = colname;

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

                switch (_type)
                {
                         case ListItemType.Item:                 

                             HyperLink ht = new HyperLink();
                             ht.Target = "_blank"; 
                             ht.DataBinding+=new EventHandler(ht_DataBinding);
                             container.Controls.Add(ht);                          

                         break;      
                }

            }

            void ht_DataBinding(object sender, EventArgs e)
            {

                HyperLink lnk = (HyperLink)sender;
                GridViewRow container = (GridViewRow)lnk.NamingContainer;
                object dataValue = DataBinder.Eval(container.DataItem, _colName);
                if (dataValue != DBNull.Value)
                {
                    lnk.Text = dataValue.ToString();
                    lnk.NavigateUrl = "http://www.booktitles.com";
                }

            }

     

    Thanks
    Sharmila
    (www.syncfusion.com)

    ASP.Net FAQ:
    http://www.syncfusion.com/faq/aspnet/default.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 22, 2006 7:57 AM
  • User-1827408301 posted

    Excellent!  I worked perfectly.  Thanks so much for your help.

    Chris

    Thursday, June 22, 2006 11:52 AM
  • User1220673890 posted

    I just tried the same thing except using textboxes inside my item templates and it works, but when I post back the columns are added again except without textboxes in the item templates. If I put the code in a if(!ISPostback) then the textboxes get removed from the columns on post back. Any ideas what problem could be?  Heres my code as I used it.

     

    foreach (string code in Codes)

    {

    TemplateField lname = new TemplateField();

    lname.HeaderText = code;

    lname.ItemTemplate = new AddTemplateToGridView(ListItemType.Item, code);

    lname.ItemStyle.Width = 30;

    gridWeek1.Columns.Add(lname);

    // }

    }

     

     

    public class AddTemplateToGridView : ITemplate

    {

    ListItemType _type;

    string _colName;

    public AddTemplateToGridView(ListItemType type, string colname)

    {

    _type = type;

    _colName = colname;

    }

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

    {

    switch (_type)

    {

    case ListItemType.Item:

    TextBox tb = new TextBox();

    tb.DataBinding += new EventHandler(tb_DataBinding);

    container.Controls.Add(tb);

    break;

    }

    }

    void tb_DataBinding(object sender, EventArgs e)

    {

    TextBox tbx = (TextBox)sender;

    tbx.Width = 30;

    //HyperLink lnk = (HyperLink)sender;

    GridViewRow container = (GridViewRow)tbx.NamingContainer;

    object dataValue = DataBinder.Eval(container.DataItem, _colName);

    if (dataValue != DBNull.Value)

    {

    tbx.Text = dataValue.ToString();

    }

    }

     

    Thanks

    Thursday, June 22, 2006 3:50 PM
  • User139906824 posted

    Either call DataBind on the gridview on the postback or recreate the gridview in Page_Init.

    The root problem is that InstantiateIn() is called when the gridview databinds.

    Thursday, July 13, 2006 8:44 AM
  • User-1252071651 posted

    what is Codes? that is used in foreach loop

    Wednesday, September 7, 2011 2:10 AM
  • User898844336 posted

    Hi,

    I've been searching online for 2 days about this and from what I understand dynamically created TemplateFields will be lost on post back.  If this is the case how are we supposed to get the values entered into the templated textboxes on Save of a button? 

    This is what I need to do:

    1. User selects from a list of locations.  I have a checkboxlist for this.
    2. Clicks on a "Enter Fee" button
    3. This will create a dynamic templated gridview with the locations as columns with textboxes to enter Fees.
    4. Clicks Save button, which will insert fee for each location into database.

    I have managed to do upto step 3.  I'm stuck at step 4.

    On click of Save button, how do I get the values user entered into textboxes?  I check to see if there are any rows in the gridview and I get 0 rows, assuming the gridview is getting lost on the post back. 

    Is there a way around this?  Am on the right track or missing something?

    Please, please help!  Any help will be greatly appreciated.

    Thank you very much.

     

    Friday, October 26, 2012 9:51 AM