locked
GridView columns with templatefield and adding controls at run time giving error if change .net framework from 3.5 to 4 RRS feed

  • Question

  • User-510697852 posted

    I have added a grid view at design time,

    <asp:GridView runat="server" ID="gvApplicableAnswerMulti" AutoGenerateColumns="False" RowStyle-HorizontalAlign="Center" 
    EnableModelValidation="True" CellPadding="4" ForeColor="#333333" GridLines="None" Width="203px" OnInit="gvApplicableAnswerMulti_Init">
    <AlternatingRowStyle BackColor="White" /> <EditRowStyle BackColor="#2461BF" /> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#EFF3FB" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> </asp:GridView>

    My code in gvApplicableAnswerMulti_Init, I am adding SectionName as item as one of the columns.

    protected void gvApplicableAnswerMulti_Init(object sender, EventArgs e)
     {
         gvApplicableAnswerMulti.Columns.Clear();
         TemplateField tfdept = new TemplateField();
         tfdept.ItemTemplate = new GridViewTemplate(ListItemType.Item, "SectionName");
         gvApplicableAnswerMulti.Columns.Add(tfdept);
          for (int i = 0; i < ((DataTable)SessiondAnsColumns).Rows.Count; i++)
              {
                 TemplateField tfchecks = new TemplateField();
                 tfchecks.HeaderTemplate = new GridViewTemplate(ListItemType.Header, 
                                          ((DataTable)SessiondAnsColumns).Rows[i]["AnsOptions"].ToString());
                 tfchecks.ItemTemplate = new GridViewTemplate(ListItemType.Item, "chk" + 
                                        ((DataTable)SessiondAnsColumns).Rows[i]["AnsOptions"].ToString());
                    gvApplicableAnswerMulti.Columns.Add(tfchecks);
    
                }
    
            }

    When i bind gvApplicableAnswerMulti to datatable,

    gvApplicableAnswerMulti.DataSource = dtAnswerSections;
    gvApplicableAnswerMulti.DataBind(); // this line following code executes

    Following code executes,

    We have GridViewPaging.cs in which GridViewTemplate calss is declared,

    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:
                        
                        if (_columnName.Contains("chk"))
                        {
                            CheckBox chkColumn = new CheckBox();
                            chkColumn.ID = _columnName;
                            chkColumn.DataBinding += new EventHandler(chkColumn_DataBinding);
                            container.Controls.Add(chkColumn);
                        }
                        else
                        {
                            Label lbColumn = new Label();
                            lbColumn.ID = "lbl" + _columnName;
                            lbColumn.DataBinding += new EventHandler(lbColumn_DataBinding);
                            container.Controls.Add(lbColumn);
                        }
                        break;
    
                    case ListItemType.EditItem:
                        break;
    
                    case ListItemType.Footer:
                        break;
                }
            }
    
            /// <summary>
            /// This is the event, which will be raised when the binding happens.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void chkColumn_DataBinding(object sender, EventArgs e)
            {
                CheckBox CBData = (CheckBox)sender;
                GridViewRow container = (GridViewRow)CBData.NamingContainer;
                object dataValue = DataBinder.Eval(container.DataItem, _columnName);
                if (dataValue != DBNull.Value)
                {
                    CBData.Checked = Convert.ToBoolean(dataValue);
                }
            }
    
            /// <summary>
            /// This is the event, which will be raised when the binding happens.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void lbColumn_DataBinding(object sender, EventArgs e)
            {
                Label lblData = (Label)sender;
                GridViewRow container = (GridViewRow)lblData.NamingContainer;
                object dataValue = DataBinder.Eval(container.DataItem, _columnName);
                if (dataValue != DBNull.Value)
                {
                    lblData.Text = dataValue.ToString();
                }
            }
        }

    For SectionName column, ITemplate.InstantiateIn() will execute and add lblColumn control will be added to each row. ID for this control will be "lblSectionName".

    Then lbColumn_DataBinding() will occur and will assign text to label control.

    Till this it is executing fine. 

    But at later stage when i try to find lblSectionName control in gridview's row's first cell i.e.

    (Label)gvApplicableAnswerMulti.Rows[0].Cells[0].FindControl("lblSectionName"); - This returns me null.

    Strange this it is working fine with framework 3.5 (it won't return me null. It finds correct control lblSectionName) but if change to framework 4 it returns me null.

    I can not understand what is happening. Anyone can guess?

    Tuesday, September 5, 2017 3:57 AM

All replies

  • User-707554951 posted

    Hi hardeshis,

    Based on your description, I new a project with framework 4.0

    I create a WebForm1 and GridViewTemplate class.

    GridViewTemplate class( completely copy the code you provided)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebApplication4
    {
        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:
    
                        if (_columnName.Contains("chk"))
                        {
                            CheckBox chkColumn = new CheckBox();
                            chkColumn.ID = _columnName;
                            chkColumn.DataBinding += new EventHandler(chkColumn_DataBinding);
                            container.Controls.Add(chkColumn);
                        }
                        else
                        {
                            Label lbColumn = new Label();
                            lbColumn.ID = "lbl" + _columnName;
                            lbColumn.DataBinding += new EventHandler(lbColumn_DataBinding);
                            container.Controls.Add(lbColumn);
                        }
                        break;
    
                    case ListItemType.EditItem:
                        break;
    
                    case ListItemType.Footer:
                        break;
                }
            }
            void chkColumn_DataBinding(object sender, EventArgs e)
            {
                CheckBox CBData = (CheckBox)sender;
                GridViewRow container = (GridViewRow)CBData.NamingContainer;
                object dataValue = DataBinder.Eval(container.DataItem, _columnName);
                if (dataValue != DBNull.Value)
                {
                    CBData.Checked = Convert.ToBoolean(dataValue);
                }
            }
    
            /// <summary>
            /// This is the event, which will be raised when the binding happens.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void lbColumn_DataBinding(object sender, EventArgs e)
            {
                Label lblData = (Label)sender;
                GridViewRow container = (GridViewRow)lblData.NamingContainer;
                object dataValue = DataBinder.Eval(container.DataItem, _columnName);
                if (dataValue != DBNull.Value)
                {
                    lblData.Text = dataValue.ToString();
                }
            }
        }
    }

    In WebForm1:

     <asp:GridView runat="server" ID="gvApplicableAnswerMulti" AutoGenerateColumns="False" RowStyle-HorizontalAlign="Center" 
    EnableModelValidation="True" CellPadding="4" ForeColor="#333333" GridLines="None" Width="203px" OnInit="gvApplicableAnswerMulti_Init1">
    
    <AlternatingRowStyle BackColor="White" />
                                                           
    <EditRowStyle BackColor="#2461BF" />
     <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
     <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
     <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
     <RowStyle BackColor="#EFF3FB" />
     <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    </asp:GridView>
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

    CodeBehind:

     protected void Page_Load(object sender, System.EventArgs e)
            {
                DataTable dtAnswerSections = new DataTable();
                dtAnswerSections.Columns.AddRange(new DataColumn[9] {
                new DataColumn("AnsOptions", System.Type.GetType("System.String")),
                 new DataColumn("SectionName", System.Type.GetType("System.String")),
                  new DataColumn("chk", System.Type.GetType("System.String")),
                     new DataColumn("chkShirt", System.Type.GetType("System.String")),
                        new DataColumn("chkTrue", System.Type.GetType("System.String")),
                         new DataColumn("chkFalse", System.Type.GetType("System.String")),
                         new DataColumn("chkAnsOptions1", System.Type.GetType("System.String")),
                          new DataColumn("chkAnsOptions2", System.Type.GetType("System.String")),
                           new DataColumn("chkAnsOptions3", System.Type.GetType("System.String")),
            });
                dtAnswerSections.Rows.Add("AnsOptions1", "SectionName1", "True", "True", "True", "True", "True", "True", "True");
                dtAnswerSections.Rows.Add("AnsOptions2", "SectionName2", "False", "False", "False", "False", "True", "True");
                dtAnswerSections.Rows.Add("AnsOptions3", "SectionName3", "True", "True", "True", "True", "True", "True", "True");
    
                gvApplicableAnswerMulti.DataSource = dtAnswerSections;
                gvApplicableAnswerMulti.DataBind();
            }
    
    
            protected void gvApplicableAnswerMulti_Init1(object sender, EventArgs e)
            {
                DataTable dtAnswerSections = new DataTable();
                dtAnswerSections.Columns.AddRange(new DataColumn[9] {
                new DataColumn("AnsOptions", System.Type.GetType("System.String")),
                 new DataColumn("SectionName", System.Type.GetType("System.String")),
                  new DataColumn("chk", System.Type.GetType("System.String")),
                     new DataColumn("chkShirt", System.Type.GetType("System.String")),
                        new DataColumn("chkTrue", System.Type.GetType("System.String")),
                         new DataColumn("chkFalse", System.Type.GetType("System.String")),
                         new DataColumn("chkAnsOptions1", System.Type.GetType("System.String")),
                          new DataColumn("chkAnsOptions2", System.Type.GetType("System.String")),
                           new DataColumn("chkAnsOptions3", System.Type.GetType("System.String")),
            });
                dtAnswerSections.Rows.Add("AnsOptions1", "SectionName1", "True", "True", "True", "True", "True", "True", "True");
                dtAnswerSections.Rows.Add("AnsOptions2", "SectionName2", "False", "False", "False", "False", "True", "True");
                dtAnswerSections.Rows.Add("AnsOptions3", "SectionName3", "True", "True", "True", "True", "True", "True", "True");
    
                gvApplicableAnswerMulti.Columns.Clear();
                TemplateField tfdept = new TemplateField();
                tfdept.ItemTemplate = new GridViewTemplate(ListItemType.Item, "SectionName");
                gvApplicableAnswerMulti.Columns.Add(tfdept);
                for (int i = 0; i < dtAnswerSections.Rows.Count; i++)
                {
                    TemplateField tfchecks = new TemplateField();
                    tfchecks.HeaderTemplate = new GridViewTemplate(ListItemType.Header,
                                            dtAnswerSections.Rows[i]["AnsOptions"].ToString());
                    tfchecks.ItemTemplate = new GridViewTemplate(ListItemType.Item, "chk" +
                                          dtAnswerSections.Rows[i]["AnsOptions"].ToString());
                    gvApplicableAnswerMulti.Columns.Add(tfchecks);
    
                }
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                Label lab = (Label)gvApplicableAnswerMulti.Rows[0].Cells[0].FindControl("lblSectionName");
                Response.Write(lab.Text);
            }

    Output:

    Best regards 

    Cathy

    Tuesday, September 5, 2017 8:45 AM
  • User-510697852 posted

    That means it's working for you. What's wrong in my project ?? 

    It's originally written under 3.5 framework. I changed to 4.0 framework without changing a single line of code. While changing anywhere i need to change any reference or anything?

    Tuesday, September 5, 2017 9:15 AM
  • User-707554951 posted

    Hi hardeshis,

    For your problem, please check the GridViewTemplate  class exited in your project after changed o framework 4.0.

    Besides, I suggest you could use F12 developer tools to check if there is a label with 'lblSectionName' id existed in your page.

    How you change your framework?

    Please follow the correct way to do change.

    https://msdn.microsoft.com/en-us/library/dd483478.aspx

    https://stackoverflow.com/questions/12726225/changing-framework-from-3-5-to-4-0-at-server

    Best regards

    Cathy

    Thursday, September 7, 2017 9:14 AM