Click here to Skip to main content
14,869,740 members
Please Sign up or sign in to vote.
1.33/5 (2 votes)
See more:
hi..

i have a gridview. i created two item TemplateField in gridview.

other two or more columns are added in gridview Dynamically using TemplateField of textbox.

XML
<asp:GridView ID="grdProductFields" runat="server" AllowPaging="false"
            AutoGenerateColumns="false" Width="100%" CssClass="mGrid" PageSize="50"
            AlternatingRowStyle-CssClass="alt" PagerStyle-CssClass="pgr"
            onrowdatabound="grdProductFields_RowDataBound"
            onrowcommand="grdProductFields_RowCommand" >
            <PagerSettings  Mode="NumericFirstLast" PageButtonCount="5"  FirstPageText="First" LastPageText="Last"/>
            <Columns>
                <asp:TemplateField HeaderText="S. No." HeaderStyle-Width="40" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:Label ID="lblSNo" runat="server" Text='<%# ((int)DataBinder.Eval(Container, "RowIndex"))+1 %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Order No." HeaderStyle-Width="100">
                    <ItemTemplate>
                        
                        <asp:TextBox ID="txtSerialno" runat="server" class="textbox" style="width:90px; vertical-align:top; margin-bottom:5px;"></asp:TextBox>
                        
                    </ItemTemplate>
                </asp:TemplateField>

                
            </Columns>
        </asp:GridView>




i am adding dynamic column with textbox using follwing code :

C#
//Iterate through the columns of the datatable to set the data bound field dynamically.
            foreach (DataColumn col in dtTemp.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, GridViewTemplate.ItemType.Textbox, col.ColumnName);

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



            //Initialize the DataSource
            grdProductFields.DataSource = dt;
            //Bind the datatable with the GridView.
            grdProductFields.DataBind();



using GridViewTemplate class for create template field.


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


//A customized class for displaying the Template Column
public class GridViewTemplate : ITemplate
{
    //A variable to hold the type of ListItemType.
    ListItemType _templateType;

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


    public GridViewTemplate(ListItemType type, string colname)
    {
        //Stores the template type.
        _templateType = type;


        //Stores the column name.
        _columnName = colname;
    }

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

        //Stores the column name.
        _columnName = colname;
    }

    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.
                container.Controls.Add(lbl);        //Adds the newly created label control to the container.
                break;

            case ListItemType.Item:
                //Creates a new text box control and add it to the container.
                        TextBox txt = new TextBox();                            //Allocates the new text box object.
                        txt.DataBinding += new EventHandler(txt_DataBinding);   //Attaches the data binding event.
                        txt.Width = 90;
                        txt.CssClass = "textbox";
                        container.Controls.Add(txt);                            //Adds the newly created textbox to the container.
                break;
            case ListItemType.EditItem:
                //As, I am not using any EditItem, I didnot added any code here.
                break;

            case ListItemType.Footer:
                CheckBox chkColumn = new CheckBox();
                chkColumn.ID = "Chk" + _columnName;
                container.Controls.Add(chkColumn);
                break;
        }
    }
}



on button click.., how to get the each textbox value to store in database..

i try some code but, this give error..

this code not recognize dynamically added columns in code behind..
normally cell index 0 or 1 are accessible this code but when we going to access next cell who is added dynamically give error.


C#
foreach (GridViewRow grdrow in grdProductFields.Rows)
        {
            TextBox txt1 = null;
            foreach (Control c in grdrow.Cells[2].Controls)
            {
                if (c != null)
                {
                    if (c.GetType() == typeof(TextBox))
                    {
                        txt1 = (TextBox)c;


                        string str = txt1.Text;
                    }

                    string strtype = c.GetType().ToString();
                }
            }

        }


please give me solution..
Posted
Comments
Guirec 3-Oct-12 9:08am
   
When you look at the generated source (before you click the button) do you have 3 <td> in per row?
AJdebugger 19-Oct-15 2:33am
   
How to change already existing control present inside itemtemplate using TemplateField instead of creating new one??

1 solution

Incase you are not adding the New field During Page_Init event, move the following code to Init Method of page.

foreach (DataColumn col in dtTemp.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, GridViewTemplate.ItemType.Textbox, col.ColumnName);
 
                //Add the newly created bound field to the GridView.
                grdProductFields.Columns.Add(bfield);
            }


Only then will the field be present during the next postback. When dynamically adding controls it should be during the Page_Init(Sometimes Page_load also works but for child controls only) method if you want that control to be present in the next postback(To be exact you have add the control in an event before LoadpostBackData event in page life cycle and only then will be IPostBachDataHandler be able to fill your control with posted back data, refer this Article).

Hope this helps.
   
v3
Comments
gmhussain007 10-Oct-12 2:04am
   
if i want to add column in gridview on conditional bases. just liske... if user click on a first button then gridview bind some different colums or if user click on second button then gridview bind some other different columns...!!

if i add some columns in gridview on Page_Init() method. so how to add different columns on different button click event.

so, how to add different columns in gridview on button click event in Page_Init() method. because Page_Init() method call only first time in page life cycle.

help me..!!
TheCoolCoder 10-Oct-12 2:11am
   
May be you can add all the required columns at once during Page_Init itself and alter the visibility later in the different button click events like: grdProductFields.Columns[3].Visible = false;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900