Add Template Column, Edit Template Column and RadDropdownlist to Grid programmatically

4 posts, 0 answers
  1. Beryl
    Beryl avatar
    8 posts
    Member since:
    Sep 2019

    Posted 18 Sep Link to this post

    I create the grid below:
    <telerik:RadGrid runat="server" ID="grdImportData" RenderMode="Lightweight" AllowPaging="true" PageSize="10" OnNeedDataSource="grdImportData_NeedDataSource" OnPageIndexChanged="grdImportData_PageIndexChanged" OnUpdateCommand="grdImportData_UpdateCommand" OnDeleteCommand="grdImportData_DeleteCommand" OnItemCommand="grdImportData_ItemCommand"  OnItemDataBound="grdImportData_ItemDataBound" AllowSorting="False" AlternatingItemStyle-BackColor="#f5f5f5" ItemStyle-BackColor="#ffffff" ColumnWidth="Auto" HorizontalAlignment="Stretch" Width="100%">
            <ClientSettings>
                <Scrolling AllowScroll="True" UseStaticHeaders="True" SaveScrollPosition="true" FrozenColumnsCount="1" EnableVirtualScrollPaging="true"></Scrolling>
                    <Resizing AllowColumnResize="true" ResizeGridOnColumnResize="true" EnableRealTimeResize="true" />
            </ClientSettings>
        <MasterTableView EditMode="InPlace" DataKeyNames="Id">
            <Columns>
                <telerik:GridEditCommandColumn  HeaderStyle-Width="75px" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"/>
                <telerik:GridTemplateColumn HeaderStyle-Width="50px">
                    <ItemTemplate>
                        <asp:LinkButton runat="server" CommandName="Delete"><i class="icon s7-junk grid-edit-icon"></i></asp:LinkButton>
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
            </Columns>
        </MasterTableView>
    </telerik:RadGrid>

     

    I then try to add a TemplateColumn, EditTemplateColumn and RadDropdownlist programmatically like below:

    protected void grdImportData_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if(ImportType == "CLEARGISTIX_ASSETS")
        {
            if (e.Item is GridDataItem)
            {
                string templateColumnName = "AssetTypeName";
                GridTemplateColumn templateColumn = new GridTemplateColumn();
                templateColumn.ItemTemplate = new MyTemplate(templateColumnName);
                templateColumn.EditItemTemplate = new MyEditTemplate();
                templateColumn.HeaderText = templateColumnName;
                templateColumn.DataField = "AssetTypeName";
     
                if (e.Item.IsInEditMode)
                {
                    RadDropDownList rddl = new RadDropDownList();
                    PortalView.LookupListBO list = LookupListBA.LookupList_GetByKey(DB_Context, "SITE_ASSETTYPE_LIST", UtilityBA.IsActiveChoice.Active);
                    List<PortalView.LookupListItemBO> oList = LookupListBA.LookupListItem_GetList_ByLookupListId(DB_Context, list.LookupListId, (Guid)Current.Employee.SiteId);
                    rddl.ID = "dropdownlist1";
                    rddl.DataSource = oList;
                    rddl.DataTextField = "Name";
                    rddl.DataValueField = "LookupListItemId";
                }
                grdImportData.MasterTableView.Columns.Add(templateColumn);
            }
        }
    }
    public class MyTemplate : ITemplate
    {
        private string colname;
        protected Label lControl;
        public MyTemplate(string cName)
        {
            colname = cName;
        }
        public void InstantiateIn(System.Web.UI.Control container)
        {
            lControl = new Label();
            lControl.ID = "lControl";
            lControl.DataBinding += new EventHandler(lControl_DataBinding);
            container.Controls.Add(lControl);
        }
     
        public void lControl_DataBinding(object sender, EventArgs e)
        {
            Label l = (Label)sender;
            GridDataItem container = (GridDataItem)l.NamingContainer;
            l.Text = ((DataRowView)container.DataItem)[colname].ToString() + "<br />";
        }
    }
     
    public class MyEditTemplate : IBindableTemplate
    {
        public void InstantiateIn(Control container)
        {
            GridEditFormItem item = ((GridEditFormItem)(container.NamingContainer));
            RadDropDownList drop = new RadDropDownList();
            drop.ID = "dropdownlist1";
     
            container.Controls.Add(drop);
        }
        public System.Collections.Specialized.IOrderedDictionary ExtractValues(System.Web.UI.Control container)
        {
            OrderedDictionary od = new OrderedDictionary();
            od.Add("LookupListItemId", ((RadDropDownList)(((GridEditFormItem)(container)).FindControl("dropdownlist1"))).DataValueField);
            return od;
        }
    }

     

    When I click on the edit button, I error: 'Unable to cast object of type 'Telerik.Web.UI.GridDataItem' to type 'Telerik.Web.UI.GridEditFormItem'.' on this line:

    od.Add("LookupListItemId", ((RadDropDownList)(((GridEditFormItem)(container)).FindControl("dropdownlist1"))).DataValueField);

    I notice that it never his the InstaniateIn code at all.

    Any assistance is greatly appreciated.

  2. Attila Antal
    Admin
    Attila Antal avatar
    376 posts

    Posted 23 Sep Link to this post

    Hi Beryl,

    The reason for the error message "Unable to cast object of type 'Telerik.Web.UI.GridDataItem' to type 'Telerik.Web.UI.GridEditFormItem'" is that the Grid uses InPlace Edit mode which utilizes the GridDataItem for editing, while the server side logic is casting it to a GridEditFormItem.

     

    Please take a look at the follow example:

    public System.Collections.Specialized.IOrderedDictionary ExtractValues(System.Web.UI.Control container)
    {
        // EditMode="InPlace"
        GridEditableItem editableItem = container as GridEditableItem;
        GridDataItem dataItem = container as GridDataItem;
    
        // EditMode = "EditForms", "WebUserControl", "Pop-Up"
        GridEditFormInsertItem insertFormItem = container as GridEditFormInsertItem;
        GridEditFormItem editFormItem = container as GridEditFormItem;
    }

     

    Also, in order to create Template columns programmatically, the entire Grid must be created in the code behind. This is described in the Creating Template Columns Programmatically article.

    "When creating template columns programmatically, the grid must be generated completely in the code-behind using the Page_Init event. Then, you must create the templates dynamically in the code-behind and assign them to the ItemTemplate and EditItemTemplate properties of the column. To create a template dynamically, you must define a custom class that implements the ITemplate interface. Then you can assign an instance of this class to the ItemTemplate or EditTemplateTemplate property of the GridTemplateColumn object."

    With that said, you will need to remove the markup and create the grid in the code behind in the Init event of the Page. If you only want to have a column conditionally, you can create it in advance and set its visibility to false when not needed.

     

    Furthermore, I am inspecting the server side code and I am trying to understand the reason behind creating a column for each grid record. If you can give me some insights, I may show you a better approach.

     

    Kind regards,
    Attila Antal
    Progress Telerik

    Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
  3. Beryl
    Beryl avatar
    8 posts
    Member since:
    Sep 2019

    Posted 23 Sep in reply to Attila Antal Link to this post

    Thanks for the response and explanation.  I tried setting the column visibility to to false, but I kept getting a binding error because when the grid first displays that named field is not a part of it.  As for why I was creating a column for each grid record, in all honesty, I was just trying to figure out how to add the column to the grid and wasn't sure where or how to do it.  Unfortunately, unless there is a way to autogenerate the rest of the  fields when creating the grid in code behind, that is not an option either.  I have found a work around for what was needed and have removed the dropdownlist from the grid completely and am using it to do a search and replace in the column.  Thanks again for your help.
  4. Attila Antal
    Admin
    Attila Antal avatar
    376 posts

    Posted 23 Sep Link to this post

    Hi Beryl,

    Could you describe us in steps the require behavior you would like to achieve? Perhaps If we understand the scenario you would like to achieve, we would show you the way.

    Kind regards,
    Attila Antal
    Progress Telerik

    Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Back to Top