Click here to Skip to main content
15,910,981 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,
I am posting my code to find control the template field. I am unable to find control the template field in the Dynamic GridView Created.

C#
public void showgrid()
    {
        GridView1.DataSource = null;
        GridView1.DataBind();
        DataTable dt = new DataTable();
        string box = "";
        
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
      //  SqlDataAdapter sda = new SqlDataAdapter();
        string floor = "Select cFloors,cFlatPerFloor from tbl_tower where ProjectID ='" + DDProject.SelectedItem.Text + "' and towerNo='" + DDTower.SelectedItem.Text + "'";
        DataTable dtv = sp.load_AnyTable(con, floor);
    
        if (dtv.Rows.Count > 0)
        {
            string flatperfloor = dtv.Rows[0][1].ToString();
            DataColumn Floor = new DataColumn("Floor", typeof(System.String));
            dt.Columns.Add(Floor);

            BoundField nameColumn = new BoundField();
            nameColumn.DataField = "Floor";
            nameColumn.HeaderText = "Floor";
            nameColumn.ReadOnly = true;
            GridView1.Columns.Add(nameColumn);
            for (int c=1; c <=(Convert.ToInt16(flatperfloor)); c++)
            {
                
                DataColumn Unit1 = new DataColumn("Unit"+c, typeof(System.String));
               dt.Columns.Add(Unit1);
               
             }
            string chk = "select Convert(int,floorNo) as FloorNo,UnitNo from tbl_tower_unit where ProjectID='" + DDProject.SelectedItem.Text + "' and towerNo='" + DDTower.SelectedItem.Text + "' and wingNo='" + DDWingNo.SelectedItem.Text + "' order by Convert(int,floorNo)";
            DataTable dtchk = sp.load_AnyTable(con, chk);
            int cFloor = Convert.ToInt16(dtv.Rows[0][0].ToString());
            for (int i=0; i <cFloor; i++)
            {
                dt.Rows.Add(i);
                int z = 1;
                for(int unitno=0;unitno<dtchk.Rows.Count;unitno++)
                {
                    if(dtchk.Rows[unitno][0].ToString()==i.ToString())
                    {
                      dt.Rows[i][z]=dtchk.Rows[unitno][1].ToString();
                      z++;
                      box = dt.Rows[i][z].ToString();
                    }
                    
                }
                
            }

            int p = 0;
           
            foreach (DataColumn col in dt.Columns)
            {
                if (p != 0)
                {
                    TemplateField tf = new TemplateField();
                    tf.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);
                    tf.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName);
                    GridView1.Columns.Add(tf);

                }
                p = 1;

            }
            p = 0;


        }
        
     //SqlCommand cmd = new SqlCommand(floor, con);
     //  //SqlCommand cmd = new SqlCommand();
     //   cmd.CommandType = CommandType.Text;
     //   //cmd.Connection = con;
     //   sda.SelectCommand = cmd;
     //   sda.Fill(dtv);
        ViewState["GridTable"] = dt;
        GridView1.DataSource = dt;
        GridView1.DataBind();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = (GridViewRow)GridView1.Rows[i];
            for (int j = 0; j <GridView1.Columns.Count; j++)
            {
                //string field_value = ((TextBox)row.Cells[1].FindControl("Unit1")).Text;//.Rows[i].Cells[j].ToString()
                //ParameterArray.Add(field_value);


                //ImageButton Button1 = (ImageButton)sender;
                //GridViewRow grdRow = (GridViewRow)Button1.Parent.Parent;
                //string strField1 = ((Label)grdRow.Cells[0].FindControl("custID")).Text;

                //if (GridView1.Rows[i].Cells[j].Text == box)
                //{
                    GridView1.Rows[i].Cells[j].Enabled = false;
                //}
                //else
                //{
                //    GridView1.Rows[i].Cells[j].Enabled = true;
                //}

            }

            //TextBox txtunit1 = ((TextBox)GridView1.Rows[i].Cells[0].TemplateControl.ClientID("MyTextBox")) as TextBox;
            //box = txtunit1.Text;
            //txtunit1.Enabled = false;
        }
    }

and the class I used for it is as follows:
C#
//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;
 
    //Constructor where we define the template type and column name.
    public GridViewTemplate(ListItemType type, 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 tb1 = new TextBox();                            //Allocates the new text box object.
              
                tb1.DataBinding += new EventHandler(tb1_DataBinding);   //Attaches the data binding event.
                tb1.Columns = 4;                                        //Creates a column with size 4.
                //for (int i = 1; i <= tb1.Columns; i++)
                //{
                //    tb1.ID = "MyTextBox" + i.ToString();
                //}
                container.Controls.Add(tb1);                            //Adds the newly created textbox to the container.
                break;

            //case ListItemType.Item1:
            //    Creates a new text box control and add it to the container.
            //    TextBox tb1 = new TextBox();                            //Allocates the new text box object.
            //    tb1.DataBinding += new EventHandler(tb1_DataBinding);   //Attaches the data binding event.
            //    tb1.Columns = 4;                                        //Creates a column with size 4.
            //    container.Controls.Add(tb1);                            //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;
        }
    }

    /// <summary>
    /// This is the event, which will be raised when the binding happens.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void tb1_DataBinding(object sender, EventArgs e)
    {
        TextBox txtdata = (TextBox)sender;
        GridViewRow container = (GridViewRow)txtdata.NamingContainer;
        object dataValue = DataBinder.Eval(container.DataItem, _columnName);
        
        if (dataValue != DBNull.Value)
        {
            txtdata.Text = dataValue.ToString();
        }
    }
}


Please can anyone of you can answer my question? The requirement is urgent for me.:confused:
Posted
Updated 24-Mar-11 19:33pm
v3
Comments
TweakBird 7-Dec-10 3:55am    
Edited for code formating and minor spellings

C#
int p = 0;

            foreach (DataColumn col in dt.Columns)
            {
                if (p != 0)
                {
                    TemplateField tf = new TemplateField();
                    tf.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);
                    tf.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName);
                    GridView1.Columns.Add(tf);

                }
                p = 1;

            }
            p = 0;


did'nt understand why you r using 'p'.

First u are assigning p=0 then in foreach loop, checking whether p!=0. This condition will not get fulfilled for the first column each time.

There may be some mistake over here.
 
Share this answer
 
Comments
Ulhas Chaudhary 25-Mar-11 5:05am    
The p i used is for the bound field which i don't want to be in edit mode
Hey I had the same issue struggled for two days , finally got it working .


page_Init we need to rebind the templete controls....


GridView.Columns.Clear();


    
    for (int colcount = 0; colcount < dtPatterns.Columns.Count; colcount++)
    {
        TemplateField ItemTmpField = new TemplateField();
        // create the header
        ItemTmpField.HeaderTemplate =
        new DynamicallyTemplatedGridViewHandler(ListItemType.Header,
                                                dt.Columns[colcount].ColumnName,
                                                dt.Columns[colcount].DataType.Name, iseditMode);
        // create ItemTemplate
        ItemTmpField.ItemTemplate =
        new DynamicallyTemplatedGridViewHandler(ListItemType.Item,
                                               dt.Columns[colcount].ColumnName,
                                                dt.Columns[colcount].DataType.Name, iseditMode);
        

            // create EditItemTemplate
            ItemTmpField.EditItemTemplate =
            new DynamicallyTemplatedGridViewHandler(ListItemType.EditItem,
                                                    dt.Columns[colcount].ColumnName,
                                                    dt.Columns[colcount].DataType.Name, iseditMode);
        
        ItemTmpField.HeaderStyle.Width = Unit.Percentage(90 / dtPatterns.Columns.Count);
        ItemTmpField.HeaderStyle.Font.Bold = true;
        PatternGridView.Columns.Add(ItemTmpField);

        // tf.HeaderStyle.Font.Bold = true;
        // tf.HeaderStyle.Width = Unit.Percentage(90 / dtPatterns.Columns.Count);

    }
   
    PatternGridView.DataSource = dt;
    PatternGridView.DataBind();
 
Share this answer
 
v2
Comments
Monjurul Habib 12-Apr-11 17:59pm    
code block added.
seenit 17-Dec-12 12:22pm    
I tried your method. But it clears all data that I input. I'm writing a function for "RowUpdating". So I have to catch the input values. Do you have any idea?

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