Dynamically create EditItemTemplate at Runtime in a GridView Control

It's very easy to implement this feature to your project:

you only must create a new class and copy the code below to this class:

 

public class DynamicallyTemplatedGridViewHandler : ITemplate

    {

        ListItemType ItemType;

        string FieldName;

        string InfoType;

 

 

public DynamicallyTemplatedGridViewHandler(ListItemType item_type, string field_name, string control_type)

        {

            ItemType = item_type;

            FieldName = field_name;

            InfoType = control_type;

        }

 implemented here the EditItem object but you can also define SelectedItems, Header, Footer etc    

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

        {

            switch (ItemType)

            {

               case ListItemType.EditItem:

                    if (InfoType == "Button")

                    {

                        ImageButton update_button = new ImageButton();

                        update_button.ID = "update_button";

                        update_button.CommandName = "Update";

                        update_button.ImageUrl = "~/images/update.gif";

                        update_button.ToolTip = "Update";

                        update_button.OnClientClick =

                          "return confirm('Are you sure to update the record?')";

                        Container.Controls.Add(update_button);

 

                        // Similarly, add a button for Cancel

 

                    }

                    else

                    // if other key and non key fields then bind textboxes with texts

                    {

                        TextBox field_txtbox = new TextBox();

                        field_txtbox.ID = FieldName;

                        field_txtbox.Text = String.Empty;

                        // if to update then bind the textboxes with coressponding field texts

                        //otherwise for insert no need to bind it with text

 

                        if ((int)new Page().Session["InsertFlag"] == 0)

                            field_txtbox.DataBinding += new EventHandler(OnDataBinding);

                        Container.Controls.Add(field_txtbox);

 

                    }

                    break;

            }

        }

 

        private void OnDataBinding(object sender, EventArgs e)

        {

            object bound_value_obj = null;

            Control ctrl = (Control)sender;

            IDataItemContainer data_item_container =

            (IDataItemContainer)ctrl.NamingContainer;

            bound_value_obj = DataBinder.Eval(data_item_container.DataItem, FieldName);

            switch (ItemType)

            {

                case ListItemType.Item:

                    Label field_ltrl = (Label)sender;

                    field_ltrl.Text = bound_value_obj.ToString();

                    break;

                case ListItemType.EditItem:

                    TextBox field_txtbox = (TextBox)sender;

                    field_txtbox.Text = bound_value_obj.ToString();

                    break;

            }

        }

    }

The usage of this class is very easy. Before you bind your GridView to a dataSource you have to call the following line for each colum which should be have a EditItemTemplate.

TemplateField ItemTmpField = new TemplateField();

 

// create the header

ItemTmpField.HeaderTemplate = new DynamicallyTemplatedGridViewHandler(ListItemType.EditItem, dt.Columns[4].ColumnName, dt.Columns[4].DataType.Name);

greets


Posted Jul 10 2007, 05:28 PM by Nadine Storandt
Filed under: , ,

Comments

Kevin Brundage wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 08-02-2007 4:28

Your article/snippet saved me a lot of time and energy.  I had most of the pieces put together and your post helped bring everything into focus.  Thanks.

Rajesh B Patil (INDIA). wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 08-21-2007 8:39

Excellent work man, keep going.

Mohasin wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 08-29-2007 14:08

In your article, I am unable to understand that Where you are calling "InstantiateIn()" from?

waitting...

Nadine Storandt wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 08-30-2007 14:50

The InstantiateIn() methode will be called when you bind the data to the grid!

yourGrid.DataBind();

greets

Toto wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 06-27-2008 8:35

Good work! Thanks!

 

brian wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 10-04-2008 2:15

In edit mode, instead of binding to a TextBox, I need to bind to a DropDownList. Please help.

Nadine Storandt wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 10-06-2008 8:56

Hey Brian,

first thanks for your support. Here is a little example how you get DropDown To work:

First of all you have to made a new switch-case construct below this: case ListItemType.EditItem:

Made a case for e.g. DropDown here is a example with a enum as dataSource:

DropDownList Select_List2 = new DropDownList();

                           Select_List2.ID = FieldName;

                           Select_List2.SelectedIndexChanged += new EventHandler(DropDownList_SelectedIndexChanged);

                           Select_List2.AutoPostBack = true;

                           Select_List2.Attributes["ctx"] = "PrintLocation";

                           Select_List2.Width = 150;

                           Select_List2.DataSource = Enum.GetNames(typeof(PrintLocation));

                           Select_List2.DataBind();

                           Select_List2.DataBinding += new EventHandler(Select_List_Click);

                           Container.Controls.Add(Select_List2);

At least you have to call this line for dropDown in EditTemplate:

// create ItemTemplate

                   ItemTmpField.ItemTemplate = new DynamicallyTemplatedGridViewHandler(ListItemType.EditItem,

                                                                 dt.Columns.ColumnName,  "DropDown");

greets

David wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 10-13-2008 17:35

Thanks for the nice article..

i have an issue. please someone help to resolve this,

After postback, the itemtemplate column disappears, if i write under not postback and even i reassign  the itemtemplate column in button click event.

if (!Page.IsPostBack)

{

ItemTmpField = new TemplateField();

           // create the header

           ItemTmpField.ItemTemplate = new DynamicallyTemplatedGridViewHandler(ListItemType.EditItem, dt.Columns[1].ColumnName, dt.Columns[1].DataType.Name);

           GridView1.Columns.Add(ItemTmpField);

           GridView1.DataSource = dt;

           GridView1.DataBind();

}

i need to take the value from textbox to str (which is a control in itemtemplate) from my button click. but while postback, the column itself getting hide. but i try to rebind the data and itemtemplate contorl in my button click, eventhen the itemtemplate is not get binding,

protected void Button1_Click(object sender, EventArgs e)

   {

       string str = ((TextBox)GridView1.Rows[0].Cells[0].FindControl("ID5")).Text;

       ItemTmpField = new TemplateField();

       DataTable dt = Session["dt"] as DataTable;

       ItemTmpField.ItemTemplate = new DynamicallyTemplatedGridViewHandler(ListItemType.EditItem, dt.Columns[1].ColumnName, dt.Columns[1].DataType.Name);

       GridView1.DataSource = dt;

       GridView1.DataBind();

   }

1) i need to have the itemtemplate column even after postbacking

2) i need to get the value from control in the itemtemplate column while button click

could anyone please help me to solve this two issues.  

Thanks in advance.

Priya wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 04-22-2011 22:18

Hi,

InstantiateIn method is not firing can any one help me on this?

Thanks,

Priya

Raj wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 04-28-2011 11:45

Can you paste your whole code in this post please?

Shriya wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 05-03-2011 19:49

Hi,

Im creating the edit itemtemplate  and itemtemplate dynamically..if enter some value in text box  template field on dynamic grid edit i lose the value on postback. And also on postback I lose all template field and i must re-create the grid.

So on each post back im recreating the Itemtemplate and Edit Item template but i dont know how to retrieve the user enter value from text box

I’m really struggling with this issue for last two days can anyone  please help me on this ???

Thanks in advance

Here is my code:

#region InvenCla Location SelectIndexChange

       /// <summary>

       /// Action on select index change of User Location Drop

       /// Instead of search button we are displaying the grid on location select index chage

       /// </summary>

       protected void InvenCalLoc_SelectIndexChanged(object sender, EventArgs e)

       {

           string errorMsg = string.Empty;

           LblMessage.Text = string.Empty;

           try

           {

               Session["InvTable"] = null;

               LoadDynamicInvenCalGrid();

           }

           catch (Exception exp)

           {

               // Log the exception.

               eAdmLogger.ExceptionLog(exp, Constants.CONFIG_EXCEPTION_POLICY, base.userID, base.appName,

                  Request.UserHostAddress, serverIP, Request.Url.AbsoluteUri);

               //Display the message to the user

               BuildLabelErrorMessage(exp.Message);

           }

       }

       #endregion

       #region Create Dynamic GridView

       /// <summary>

       /// This mehod is for Assign the header text value and create the item template,edittemplate dynamically for the grid view

       /// </summary>

       public void LoadDynamicInvenCalGrid()

       {

           try

           {

               DateTime posdate = DateTime.MinValue;

               DataTable dt = new DataTable();

               PositionSystemControlBLManager scBLManager = new PositionSystemControlBLManager();

               InvenCalGrid.Columns.Clear();

               if (InvenCalPosDate.Text != "")

               {

                   posdate = Convert.ToDateTime(InvenCalPosDate.Text.Trim());

                   posdate = posdate.AddDays(-1);

               }

               if (Session["InvTable"] == null)

anil wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 05-24-2011 6:27

i am having problem with the edititem, i cannot retrieve the value of textbox in edititem in RowUpdating event of the gridview.

Can anyone help me?

Nadine Storandt wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 05-26-2011 11:54

Hi anil,

you bind the value of the editItem to a readOnlyItem (Label).

So you have to implement the method:

"private void OnDataBinding(object sender, EventArgs e)"

with the Case ListItemType.Item

Then you can use the label for retrieving data from the desired field on RowUpdating.

cheers

Jer wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 07-18-2012 8:41

Hi all,

What if i want to add 2 or more control in 1 TemplateField? is that possible? Example is this markup

<asp:TemplateField HeaderText="Overall Margin">

                               <ItemTemplate>

                                   <asp:Label ID="lblOverallMargin" runat="server" />

                               </ItemTemplate>

                               <EditItemTemplate>

                                   <asp:TextBox ID="txtOverallMargin" runat="server" />

                               </EditItemTemplate>

                           </asp:TemplateField>

is it possible to do this in Code Behind? 1 templatefield has ITEMTEMPLATE and EDITITEMTEMPLATE.

thanks!!

Prabhash wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 12-04-2012 13:47

Hi,

i m not able to make the event drpdwn_selectedindexchanged

to get fired when i select something in dropdown and on seleting any value the gridview also gets dissappeared...Could you help me.

Thanks!

Namrata wrote re: Dynamically create EditItemTemplate at Runtime in a GridView Control
on 01-10-2013 18:55

The instantiatein method does not indentiy the edititemtemplate. I am doing exactly the same thing as in this code. What could be the problem.

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
developers.de is a .Net Community Blog powered by daenet GmbH.