RadGrid Runtime Columns

28 posts, 0 answers
  1. Kris
    Kris avatar
    9 posts
    Member since:
    Jun 2008

    Posted 26 Jun 2008 Link to this post

    I'm working on creating an asp.net user control that contains a RadGrid.  Within the user control I want to define the columns in the RadGrid at runtime.  When the grid loads, if the page is not a postback, I generate and add the required columns to the grid.  So far this works as expected.  When the page displays the appropriate columns are visible.  However, when a postback occurs (paging, sorting, etc...) some of the column structure is lost.  For example, when I click on one of the column headers to sort the column, a postback occurs and when the page refreshes on the screen the column header text for every column is blank and the data is not sorted.  Another issue is that when I click the next page button, the postback occurs, the page changes but again the header text for every column is missing and the data in each cell shows "System.Data.DataRowView".  In some of my debugging I've found that when the page posts back on a page index change, each of the GridBoundColumn objects in the grid have lost their DataField property value and the HeaderText property value.  They do however keep their UniqueName property value.

    Am I missing somthing to insure that these columns maintain their state upon postback?
  2. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 27 Jun 2008 Link to this post

    Hi Kris,

    How do you bind Grid? Try binding the Grid in the NeedDataSource event. Grid features like Filtering ,Sorting etc work with AdvancedDataBinding techniques. Go through the following online demo to get more details about AdvancedDataBinding techniques.
    Advanced data-binding

    Shinu.
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Kris
    Kris avatar
    9 posts
    Member since:
    Jun 2008

    Posted 27 Jun 2008 Link to this post

    Thanks for the reply.  Unfortunately, it's not the binding that I'm having a problem with.  The problem is that durring a postback the grid is not remembering the details of the columns I've added at runtime.  It remembers that the columns exist, but information such as the DataField and HeaderText are reset to "".

    FYI... I am using the NeedDataSource event to set the DataSource property to my dataview.  This is working as expected.  I've proven this by defining one column at design time and adding the rest of the columns at runtime.  With this setup the paging and sorting work only with the hard coded column.  The rest of the columns loose their headers and the data in those columns reverts to the object name ("System.Data.DataRowView") since the column has lost it's DataField value.

    Do you have any examples of a RadGrid adding GridBoundColumns at runtime and using the paging and the sorting?
  5. Vlad
    Admin
    Vlad avatar
    11100 posts
  6. Clifford
    Clifford avatar
    1 posts
    Member since:
    Aug 2008

    Posted 26 Aug 2008 Link to this post

    I am having the same problem.  Here is my page:
    1 <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="TableAdmin.aspx.cs" Inherits="Manage_WMSAdmin_TableAdmin" Title="Untitled Page" %> 
    2  
    3 <%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %> 
    4 <asp:Content ID="Content1" ContentPlaceHolderID="HeaderContent" Runat="Server">  
    5 </asp:Content> 
    6 <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">  
    7     <telerik:RadScriptManager id="ScriptManager" runat="server" /> 
    8     <telerik:RadGrid ID="RadGrid1" runat="server" AllowFilteringByColumn="True" AllowPaging="True" 
    9         AllowSorting="True" AutoGenerateColumns="False" AutoGenerateDeleteColumn="True" 
    10         AutoGenerateEditColumn="True" GridLines="None" OnNeedDataSource="RadGrid1_NeedDataSource" AllowMultiRowEdit="True" ShowStatusBar="True">  
    11         <ClientSettings> 
    12             <Scrolling AllowScroll="True" UseStaticHeaders="True" /> 
    13         </ClientSettings> 
    14         <MasterTableView EditMode="InPlace">  
    15             <EditFormSettings> 
    16                 <PopUpSettings ScrollBars="None" /> 
    17             </EditFormSettings> 
    18             <ExpandCollapseColumn Resizable="False" Visible="False">  
    19                 <HeaderStyle Width="20px" /> 
    20             </ExpandCollapseColumn> 
    21             <RowIndicatorColumn Visible="False">  
    22                 <HeaderStyle Width="20px" /> 
    23             </RowIndicatorColumn> 
    24         </MasterTableView> 
    25     </telerik:RadGrid> 
    26 </asp:Content> 
    27  
    28  
     and here is my code behind:
    1 using System;  
    2 using System.Data;  
    3 using System.Configuration;  
    4 using System.Collections;  
    5 using System.Web;  
    6 using System.Web.Security;  
    7 using System.Web.UI;  
    8 using System.Web.UI.WebControls;  
    9 using System.Web.UI.WebControls.WebParts;  
    10 using System.Web.UI.HtmlControls;  
    11 using TheCognetGroup.DataAccess.Gateway;  
    12 using Telerik.Web.UI;  
    13 using System.Collections.Generic;  
    14  
    15 public partial class Manage_WMSAdmin_TableAdmin : System.Web.UI.Page  
    16 {  
    17     protected void Page_Load(object sender, EventArgs e)  
    18     {  
    19         BuildTableColumns();  
    20         if (!IsPostBack)  
    21         {  
    22         }  
    23     }  
    24  
    25     private void BuildTableColumns()  
    26     {  
    27         IGateway LocationBO = GatewayFactory.findGateway("LocationTable""WMS");  
    28         IAttributeTypeMap[] keys = LocationBO.findKeyFields();  
    29         List<string> dataKeyNames = new List<string>(keys.Length);  
    30         foreach (IAttributeTypeMap key in keys)  
    31         {  
    32             dataKeyNames.Add(key.Name);  
    33         }  
    34         RadGrid1.MasterTableView.DataKeyNames = dataKeyNames.ToArray();  
    35  
    36  
    37         RadGrid1.MasterTableView.Width = Unit.Percentage(100);  
    38  
    39         foreach (IAttributeTypeMap attrib in LocationBO.Attributes)  
    40         {  
    41             Boolean IsNewColumn = false;  
    42             GridBoundColumn boundColumn = RadGrid1.MasterTableView.Columns.FindByUniqueNameSafe(attrib.Name) as GridBoundColumn;  
    43             if (boundColumn == null)  
    44             {  
    45                 boundColumn = new GridBoundColumn();  
    46                 IsNewColumn = true;  
    47             }  
    48             boundColumn.UniqueName = attrib.Name;  
    49             boundColumn.DataField = attrib.Name;  
    50             boundColumn.HeaderText = attrib.Name;  
    51             boundColumn.DataType = attrib.FieldType;  
    52             boundColumn.ReadOnly = attrib.IsReadOnly && dataKeyNames.Contains(attrib.Name)==false;  
    53             if (IsNewColumn)  
    54                 RadGrid1.MasterTableView.Columns.Add(boundColumn);  
    55         }  
    56     }  
    57     protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)  
    58     {  
    59         IGateway LocationBO = GatewayFactory.findGateway("LocationTable""WMS");  
    60  
    61           
    62         RadGrid1.DataSource = LocationBO.loadAll().Tables[0];  
    63     }  
    64 }  
    65  
    When the user clicks on the column to sort, the header loses its text.  I am using Telerik.Web.UI version 2008.01.0415.20
  7. Sebastian
    Admin
    Sebastian avatar
    9934 posts

    Posted 27 Aug 2008 Link to this post

    Hi Clifford,

    From your code snippets you provided I see that our dynamic column creation does not conform to the conventions listed in these articles from the RadGrid documentation:

    http://www.telerik.com/help/aspnet-ajax/grid-programmatic-creation.html
    http://www.telerik.com/help/aspnet-ajax/ajax-most-common-mistakes.html (the first paragraph)

    Note that when you choose to generate the columns programmatically on PageLoad, you have to do that inside !Page.IsPostBack condition and add the columns to the Columns collection before defining their properties. Most probably this is the reason for the corrupted viewstate of your columns and the missing header text.

    Please review your code and let us know whether this helps.

    Best regards,
    Stephen
    the Telerik team

    Check out Telerik Trainer, the state of the art learning tool for Telerik products.
  8. caglar_ozkul
    caglar_ozkul avatar
    111 posts
    Member since:
    Sep 2006

    Posted 10 Sep 2008 Link to this post

    Hi,

    I have similar problem. In my case: There is a custom WebControl MyList that contains a RadGrid. MyList has a FieldCollection property (Fields). Each Fied holds column information and some useful data. I am creating my grid structure in on_init method. But in some cases, it is needed to add dynamic columns. And some times dynamic template columns.

    To achieve this, I have to use Page_Load event. I can not use Page_Init, Because i can not access database during Page Initialization because of Enterprise Library UIP. During initialization the Controller (MVC pattern) is null.
    The process order is below:
    1- Define MyList Static structure in .aspx
    2- Define MyList Static Fields in .aspx
    3- Use MyList.Fields.Add(MyField) in Page_Load event.

    Fields.Add method calls AddColumn method of Grid. it creates Telerik GridColumn and adds it to the MasterTableView's Column Collection.

    The problem is:
    Each Ajax Request that updates the Grid causes to additional columns to be added to grid. (The additional column count is equals to my dynamic columns count, For 3 dynamic column, each request adds 3 more columns to my grid) MyList control uses its own viewstate to hold Fields. I guess RadGrid too. And i guess the grid's viewstate causes the problem.

    If i use EnableViewState = false of grid everything is ok. Except I have to Bind grid each ajax request that ajaxified with grid. But It is not what i want. Say: there is a toolbar on top of the grid. And The toolbar ajaxified with grid. Some toolbar buttons have no affect on grid (I can not expose ToolbarButton from toolbar ajaxified controls). I would probably use Grid.DataSource = ... for just one ToolbarButton. This is why i dont want to use NeedDataSource... (I know you are very sensetive about OnNeedDataSource but I don't want to use it. I can explain it more detail if you want.)

    This was my first question. (DisableColumnsViewState property can solve my both problems I guess.)

    The second is:

    In RadGrid documentation there is written that:
    Column templates must be added in the Page_Init event handler, so that the template controls can be added to the ViewState.

    Really the situation is worse, if i use Dynamic Template Columns. It adds Empty colums. I guess the sentence int the documentation is related with this problem. As I explained before I have to use template columns. and I have to add them in Page_Load event. Is there a way for this problem?

    Kind Regards,
    Caglar Ozkul
  9. caglar_ozkul
    caglar_ozkul avatar
    111 posts
    Member since:
    Sep 2006

    Posted 10 Sep 2008 Link to this post

    Ooops there is a property named EnableColumnsViewState.
    "I wish, I request another thing from god" He loves me. :P  I guess my problem has been solved. Thanks for this property.

    Kind Regards,

  10. Carl
    Carl avatar
    5 posts
    Member since:
    May 2009

    Posted 28 Jul 2009 Link to this post

    I just wanted to post something to "second" a solution, so to speak, from admin.  The solution of "add the columns to the Columns collection before defining their properties. Most probably this is the reason for the corrupted viewstate of your columns and the missing header text" solved my problem immediately.  I was trying the google type ahead example and saw that they were adding the column to the grid before adding properties but I thought to myself, "I'm going to make it clean and add the column to the grid after adding all my properties."  MISTAKE. 
    Note; I do not have my method call inside of an If(!this.Page.IsPostBack) and it works just fine.  The grid I'm working on is very complicated with a good amount of formating happening in the code behind and putting that call inside of a postback check broke some of the formating.
    Just wanted to give a nod to the solution.  Try it!
  11. hamid bahan
    hamid bahan avatar
    9 posts
    Member since:
    Mar 2010

    Posted 23 May 2010 Link to this post

    thank you carl
    your suggestion help me
    i wish telerik team use your suggestion and imporve dynamic column adding code

  12. Desiree
    Desiree avatar
    6 posts
    Member since:
    Jan 2011

    Posted 13 Jan 2011 Link to this post

    I agree. This "needing to call add prior to setting properties" is shoddy and leads to subtle hard-to-reason quirks. It's especially confusing to be an "advanced" developer and running into all the forum replies on the "recommend practice" without a valid explanation for why this approach is required -- wasted over an hour of my time because I thought "it couldn't be that dumb". I was wrong.

    Please fix this awful behavior to COPY/USE any set properties at time of "Columns.Add". Thanks.
  13. Sebastian
    Admin
    Sebastian avatar
    9934 posts

    Posted 14 Jan 2011 Link to this post

    Hello guys,

    In addition to the links to the help topics Stephen provided in his post, we have a separate section in the RadGrid online demos targeting its dynamic generation (under node "Programmatic creation"). Those resources explain how to build the grid at runtime and the concepts you need to follow to ensure that its viewstate and column structure will remain intact across postbacks.

    Best regards,
    Sebastian
    the Telerik team
    Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.
  14. Desiree
    Desiree avatar
    6 posts
    Member since:
    Jan 2011

    Posted 14 Jan 2011 Link to this post

    Thank you for the comprehensive demos and examples. They make the Telerik controls usable.

    However, repeated linking to examples misses several key points and also propagates some "incorrect" ordering of operations (I am using 2010Q3 1215). It should be noted that the demos all add the dynamic columns ON EACH POSTBACK and so the ordering issue is not apparent in those cases, as mentioned below. The "buggy" method of column adding is also found here http://www.telerik.com/help/aspnet-ajax/t_telerik_web_ui_gridcolumncollection.html. In the next section I will explain the particular issue. Please DO NOT SEND ME ANOTHER DEMO LINK. Thanks.

    The issue I am talking about is related to a subtle bug caused in the ORDERING of the operations, as described below. As pointed out before, here is the case that does work without re-adding dynamic columns on each page-load by using the column view-state built into the MasterView.

    Ensure that EnableColumnsViewState is enabled in the MasterTableView (this is the default setting)
    THEN IN THIS PRECISE ORDER:
    1. Create a new GridColumn
    2. Add the column to the master table view
    3. Set the properties of the column
    If you switched around #2 and #3 you've now just broken columns across post-backs! The column data will be set on the first rendering (which will lead to a "false positive" that the approach is working) -- however, after a post-back none of their values (such as HeaderText or GroupingExpression) will be restored. It is as if the column values where not being propagated to the view-state correctly. Hmm.

    This the mis-feature which should be classified as a bug. It is also not consistently covered. I have found this MIS-BEHAVIOR mentioned in one-off places occasionally (sometimes by a Telerik team-member, other times by other forum users, as in one of the preceding posts). However the repeated "just copy and paste this demo code" neither addresses nor resolves the issues.

    Again, THE PROBLEM is two-fold
    1. The ordering of adding the GridColumn and assignment of properties matters. This is a bug in the current implementation. At the very least the operation order of #2 and #3 above should be commutative, as what might be expected.
    2. The documentation/examples are incorrect and/or misleading in the fact that they do not make mention of #1. The demos work only in the "copy and paste" of the demo code -- but not when using the internal MasterTableView column view state. Since the "order" is wrong in the demos, any copy-and-paste from the demos, with just the change to the internal column view state will result in the incorrect behavior described above.
    In fact, I would go so far as to say that:
    The mis-understanding and mis-reporting of this BUG leads to the demos and examples being written as they are INSTEAD of taking advantage of the internal column view state. The problem is self-perpetuating and an inferior "solution" is promoted as the copy'n'paste example.

    Please do accept some of the bugs/issues I have brought up so that the Telerik product can be improved.
    Again, no "demo" or "documentation" link is required.
    Thanks.
  15. Desiree
    Desiree avatar
    6 posts
    Member since:
    Jan 2011

    Posted 14 Jan 2011 Link to this post

    Oops, I stand corrected. In the "OnPageLoad" example (http://demos.telerik.com/aspnet-ajax/grid/examples/programming/groupby/defaultcs.aspx)

    The column adding ordering is as described to avoid the bug mentioned in the previous post:

                    boundColumn = new GridBoundColumn();
                    RadGrid1.MasterTableView.Columns.Add(boundColumn);                
                    boundColumn.DataField = "CustomerID";
                    boundColumn.HeaderText = "CustomerID";


    And there is one small comment as to this ordering being mandated:

    "We follow the rules for structure object generation: columns or detail tables should be added to the corresponding collection first and then values for the properties of this instance should be set".

    This is in extra small print in the description area mixed in with other verbage, and where "the rules" are defined, I have no idea.

    Again, this non-commutative behavior/bug is not expected and should be resolved in a future release. In the meantime, prominent warnings should should inserted into all the appropriate API documentation and example code about this quirk.
  16. Sebastian
    Admin
    Sebastian avatar
    9934 posts

    Posted 17 Jan 2011 Link to this post

    Hello Desiree,

    Thank you for the detailed explanation - I understand your concerns and agree that notes/warnings should be present in the API reference when code concerning grid dynamic creation is included. I will notify our documentation writers for that to gradually inject such comments in the RadControls for ASP.NET AJAX server API docs for the next versions of the components.

    In addition, I would like to draw your attention to the following paragraphs explaining how to build the RadGrid structure at runtime (on PageLoad or PageInit respectively):

    Creating the grid entirely in the code behind

    When generating RadGrid instance entirely in code, you should use the Page_Init or Page_Load event handlers. 

    Creating RadGrid on Page_Load

    When creating RadGrid on Page_Load event, the columns or detail tables should be added to the corresponding collection first and then values for the properties of this instance should be set. Remember to check the condition (Not IsPostBack) to avoid adding the same structure objects to the grid twice. This is important because no ViewState is managed for the object before it has been added to the corresponding collection.


    Creating RadGrid on Page_Init

    When generating a grid in the Page_Init event handler, grid columns should be added to the Controls collection of the MasterTableView after their attributes are set. No ViewState is required for grid structure to be persisted as it is recreated on each page initialization.

    They summarized the main concepts that one has to conform to in order to ensure that the viewstate and column structure of the control will be consistent.

    Kind regards,
    Sebastian
    the Telerik team
    Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.
  17. Fernando
    Fernando avatar
    1 posts
    Member since:
    Mar 2011

    Posted 22 Mar 2011 Link to this post

    Hola equipo Telerik,

    Yo tengo un problema parecido, tengo que crear dos columnas en tiempo de ejecución, pero necesito ordenarlas después de las columnas que han sido creadas con la colección de datos que ha sido insertada en el RadGrid con anterioridad. Por que las columnas que creo en tiempo de diseño las muestra primero y después las columnas del origen de datos.

    PD. estas columnas deben de contener links para llevar a otra pagina.¿Los registros que se crean en tiempo de diseño o en tiempo de diseño y en tiempo de ejecución adquieren las propiedades del registro en el que se insertaron es decir si dicho link contiene el ID del registro donde esta?

    Espero que puedan ayudarme Equipo Telerik.
  18. Larry
    Larry avatar
    6 posts
    Member since:
    Oct 2010

    Posted 17 May 2011 Link to this post

    I have a similar problem, but with a twist.
    I have a heirarchical RadGrid, that contains a NestedViewTemplate, (which consists of a RadTabStrip and a RadGrid).  I am modeling this structure similar to the Telerik sample for a "Heirarchy With Templates" example:
    http://demos.telerik.com/aspnet-ajax/grid/examples/hierarchy/nestedviewtemplate/defaultcs.aspx

    The suggested "best practices" cannot work in my case because I don't have access to my "inner" grid in the Page_Load or Page_Init events.

    Also, I don't use RadPageView with the RadTabStip, I'm simply using the RadTabStrip's selected tab to determine which data to load for the RadGrid.  (instead of having multiple pageViews each with a RadGrid in it).  By the way, the RadTabStrip is databound, and the data source is dependent on the parent grid row's data.
    However, I need the child/inner RadGrid to have dynamic columns based on what columsn are available from my data source (I'm using POCO objecs and using the NeedDataSource event to populate the grid.)

    I am not experiencing any runtime errors, and my technique seems to almost work.  I am modifying the grid's columns in teh NeedDataSource event.
    When I expand the first row in the root grid, the RadTab and child grid display properly with the correct columns.  The problem I am experiencing is that when I have a postback due to the root grid nodes expanding, or the tab selection causing the child grid data source to change, the columns of all child grids are recomputed, and I can figure out which grid event to use to recompute the columns.  I have tried modifying the grid columns in the "NeedDataSource", "Load" and PreRender events.  I don't get any errors, and at the end fo the event handler, teh columns appear to be correct, but when the grid is displayed, the columns have reverted back to the "design" time configuration.
  19. Larry
    Larry avatar
    6 posts
    Member since:
    Oct 2010

    Posted 17 May 2011 Link to this post

    One more note:
    I was able to figure out how to get into the "Page_Load" event an handle creating the dynamic columns.
    However, when the page is finally displayed, the only "child" grid that has the correct dynamic columns (rather than the "design time" columns).
    I was able to set a break point in the child grids' "PreRender" event and it appears that the columns are set correctly, but it's not displaying as I wanted.  Is there a different point at which I need to handle this column creation?

    I should state that I am not creating all of the grid's columns at run time.  I am modifying some of the columns in middle of the grid.  I'm deleting two columsn at index 4 & 5, and adding one or more columns at position 4.
  20. Raji
    Raji avatar
    56 posts
    Member since:
    Jul 2011

    Posted 01 Jul 2011 Link to this post

    I also have the same problem. When I load the grid first time its fine. When I click on the columns to sort, it sorts fine but adds the columns again to the grid. I would appreciate if I can get some help. I am attaching the code below. I am using the .net 2.0 dll version Telerik.Web.UI.dll(2010.3.1317.20)

    RadGridFIlter.cs(code below):

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Telerik.Web.UI;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;
    using System.Data;
    using System.Configuration;

    namespace RadWebUIControls
    {
        /// <summary>
        /// Summary description for RadGridFilter.
        /// </summary>
        public class RadGridFilter:RadGrid
        {
            public RadGridFilter()
                : base()
      {           
            }

            public void CreateDataGrid(System.Data.DataSet dsQDFields)
            {
                this.ID = "RadWorkItemDataGrid";
                //this.Columns.Clear();

                this.ShowStatusBar = true;
                this.AutoGenerateColumns = false;
                this.MasterTableView.PageSize = 50;
                this.AllowSorting = true;
                this.AllowMultiRowSelection = false;
                this.AllowPaging = true;
                //this.EnableViewState = false;
               
               
                //this.AllowAutomaticDeletes = true;
                //this.AllowAutomaticInserts = true;
                //this.AllowAutomaticUpdates = true;
                this.GridLines = GridLines.None;

                this.PagerStyle.Mode = GridPagerMode.NumericPages;

                this.MasterTableView.DataKeyNames = new string[] { "EmployeeID" };

                this.AddTemplateColumn(this.SelectWorkItemTemplateColumn());
                this.AddTemplateColumn(this.ViewImageTemplateColumn());

                foreach (DataRow drQRow in dsQDFields.Tables[0].Rows)
                {
                    if (drQRow["DataTypeName"].ToString().ToUpper().Equals("DATE"))
                    {
                        //this.AddBoundColumn(drQRow["FieldName"].ToString(), drQRow["FieldName"].ToString(), drQRow["FieldDisplayName"].ToString(), true, System.Web.UI.WebControls.HorizontalAlign.Left, System.Web.UI.WebControls.VerticalAlign.Middle, false, "{0:MM/DD/YYYY}",Convert.ToInt16(drQRow["GridColSize"]));
                        this.AddBoundColumn(drQRow["FieldName"].ToString(), drQRow["FieldName"].ToString(), drQRow["FieldDisplayName"].ToString(), true, System.Web.UI.WebControls.HorizontalAlign.Left, System.Web.UI.WebControls.VerticalAlign.Middle, false, "{0:d}",0);
                    }
                    else
                    {
                        //this.AddBoundColumn(drQRow["FieldName"].ToString(), drQRow["FieldName"].ToString(), drQRow["FieldDisplayName"].ToString(), true, System.Web.UI.WebControls.HorizontalAlign.Left, System.Web.UI.WebControls.VerticalAlign.Middle, false, "", Convert.ToInt16(drQRow["GridColSize"]));
                        this.AddBoundColumn(drQRow["FieldName"].ToString(), drQRow["FieldName"].ToString(), drQRow["FieldDisplayName"].ToString(), true, System.Web.UI.WebControls.HorizontalAlign.Left, System.Web.UI.WebControls.VerticalAlign.Middle, false, "",0);
                    }

                    if (!drQRow.IsNull("HideColumn") && Convert.ToInt16(drQRow["HideColumn"]) == 1)
                    {
                        HideColumn(drQRow["FieldDisplayName"].ToString());
                    }
                }

                this.AddTemplateColumn(this.EditWorkItemTemplateColumn());
                //this.EnableSorting(System.Drawing.Color.White);

            }

            //public void LoadData(DataSet pData, string sFilter, string pSortOrder, string pSelectedItems, string pLastItemViewed, string pUserName, string pStepName, string pObjectStore, string pQType)
            public void LoadData(DataTable pData, string sFilter, string pSortOrder)
            {

                this.VirtualItemCount = pData.Rows.Count;
        
                pData.DefaultView.Sort = pSortOrder;
                if (sFilter != null && !sFilter.Equals(string.Empty))
                    pData.DefaultView.RowFilter = sFilter;
              
                this.DataSource = pData.DefaultView;
                this.DataBind();

              
           
            }

    /// <summary>
            /// Add template column
            /// </summary>
            public void AddTemplateColumn(GridTemplateColumn pTemplateColumn)
            {
                this.MasterTableView.Columns.Add(pTemplateColumn);
            }

            /// <summary>
            /// Add bound column
            /// </summary>
            public void AddBoundColumn(string pDataField, string pSortExpression, string pHeaderText, bool pReadOnly, HorizontalAlign pHalign, VerticalAlign pValign, bool pWrap, string pFormat, int pWidth)
            {
                GridBoundColumn column = new GridBoundColumn();
              
                //BoundColumn column = new BoundColumn();
                column.HeaderText = pHeaderText;
                column.DataField = pDataField;
                column.ReadOnly = pReadOnly;
                column.UniqueName = pDataField;
                column.ItemStyle.Wrap = pWrap;
                column.ItemStyle.VerticalAlign = pValign;
                column.ItemStyle.HorizontalAlign = pHalign;
                if (pWidth > 0)
                    column.ItemStyle.Width = Unit.Pixel(pWidth);
                column.SortExpression = pSortExpression;
                if (pFormat != String.Empty)
                    column.DataFormatString = pFormat;
                //this.Columns.Add(column);

                this.MasterTableView.Columns.Add(column);

            }
            /// <summary>
            /// Hide the column.
            /// </summary>
            public void HideColumn(string pHeaderText)
            {
                for (int _i = 0; _i < this.MasterTableView.Columns.Count; _i++)
                {
                    if (this.MasterTableView.Columns[_i].HeaderText.IndexOf(pHeaderText) >= 0)
                    {
                        this.MasterTableView.Columns[_i].Visible = false;
                        break;
                    }
                }
            }
            /// <summary>
            /// Show the column.
            /// </summary>
            public void ShowColumn(string pHeaderText)
            {
                for (int _i = 0; _i < this.MasterTableView.Columns.Count; _i++)
                {
                    if (this.MasterTableView.Columns[_i].HeaderText.IndexOf(pHeaderText) >= 0)
                    {
                        this.MasterTableView.Columns[_i].Visible = true;
                        break;
                    }
                }
            }
           
            /// <summary>
            /// Hide the Select column.
            /// </summary>
            public void HideSelect()
            {
                this.HideColumn("Select");
            }
            /// <summary>
            /// Show the Select column.
            /// </summary>
            public void ShowSelect()
            {
                this.ShowColumn("Select");
            }

            /// <summary>
            /// Hide the View column.
            /// </summary>
            public void HideViewWorkItem()
            {
                this.HideColumn("View");
            }
            /// <summary>
            /// Show the View column.
            /// </summary>
            public void ShowViewWorkItem()
            {
                this.ShowColumn("View");
            }
            /// <summary>
            /// Show the Process column.
            /// </summary>
            public void ShowProcessWorkItem()
            {
                this.ShowColumn("Process");
            }
            /// <summary>
            /// Hide the Process column.
            /// </summary>
            public void HideProcessWorkItem()
            {
                this.HideColumn("Process");
            }

            public int GetSelectedRowIndexForJavascript(int pItemIndex)
            {
                int _selectRow = (pItemIndex + 1);
                if (this.AllowPaging &&
                    this.PagerStyle.Visible &&
                    (this.PagerStyle.Position == GridPagerPosition.Top || this.PagerStyle.Position == GridPagerPosition.TopAndBottom))
                {
                    _selectRow = (pItemIndex + 2);
                }
                return _selectRow;
            }

            protected GridTemplateColumn SelectWorkItemTemplateColumn()
            {
                GridTemplateColumn _tmpCol = new GridTemplateColumn();
                _tmpCol.ItemTemplate = new SelectWorkItemColumn();
                _tmpCol.ItemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
                _tmpCol.HeaderText = "Select";
                _tmpCol.UniqueName = "SelectWorkItem";
                return _tmpCol;
            }

            protected GridTemplateColumn EditWorkItemTemplateColumn()
            {
                GridTemplateColumn _tmpCol = new GridTemplateColumn();
                _tmpCol.ItemTemplate = new EditWorkItemColumn();
                _tmpCol.HeaderText = "Process";
                _tmpCol.ItemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
                _tmpCol.UniqueName = "EditWorkItem";
                return _tmpCol;
            }

            protected GridTemplateColumn ViewImageTemplateColumn()
            {
                GridTemplateColumn _tmpCol = new GridTemplateColumn();
                _tmpCol.HeaderText = "View";
                _tmpCol.HeaderStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
                _tmpCol.ItemTemplate = (new ViewWorkItemImageColumn());
                _tmpCol.ItemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
                _tmpCol.UniqueName = "ViewDocument";
                return _tmpCol;
            }

        }

        /// <summary>
        /// Summary description for SelectWorkItemColumn
        /// </summary>
        public class SelectWorkItemColumn : System.Web.UI.ITemplate
        {
            public void InstantiateIn(System.Web.UI.Control container)
            {
                CheckBox _select = new CheckBox();
                _select.ID = "SelectWorkItem";
                container.Controls.Add(_select);
            }
        }
        /// <summary>
        /// Summary description for EditWorkItemColumn
        /// </summary>
        public class EditWorkItemColumn : System.Web.UI.ITemplate
        {
            public void InstantiateIn(System.Web.UI.Control container)
            {             
                HyperLink _edit = new HyperLink();
                //_edit.Target = "_BLANK";
                _edit.Text = "Process";
                _edit.Attributes.Add("target", "_blank");
                _edit.ID = "EditWorkItem";
                _edit.CssClass = "DataGridLinkButton";
                container.Controls.Add(_edit);
            }
        }
        /// <summary>
        /// Summary description for ViewWorkItemImageColumn
        /// </summary>
        public class ViewWorkItemImageColumn : System.Web.UI.ITemplate
        {
            public void InstantiateIn(System.Web.UI.Control container)
            {
                LinkButton _view = new LinkButton();
                _view.Text = "View";
                _view.ID = "ViewImage";
                _view.CssClass = "DataGridLinkButton";
                container.Controls.Add(_view);
            }
        }
    }

    CustomRadGrid.aspx(Code below):

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CustomRadGrid.aspx.cs" Inherits="CustomRadGrid" %>
    <%@ Register TagPrefix="radweb" Namespace="RadWebUIControls" Assembly="RadWebUIControls" %>
    <%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <telerik:RadScriptManager ID="RadScriptManager1" runat="server" />
            <div>
                <radweb:RadGridFilter ID="WorkItemDataRadGrid" runat="server" > </radweb:RadGridFilter>
                <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
                </telerik:RadAjaxManager>
            </div> 
        </form>
    </body>
    </html>

    CustomRadGrid.aspx(Code behind below):

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;
    using Telerik.Web.UI;

    public partial class CustomRadGrid : System.Web.UI.Page
    {
        public static DataTable dtTable;
        protected void Page_Load(object sender, EventArgs e)
        {
            RadAjaxManager1.AjaxSettings.AddAjaxSetting(WorkItemDataRadGrid, WorkItemDataRadGrid);
            if (!this.IsPostBack)
            {
                LoadData1();
            }  
          
           
        }

        private void LoadData1()
        {
            //DataSet dsTemp = new DataSet();
            if (ViewState["WorkItemsList"] == null)
            {
              
            SqlConnection SqlConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ToString());
            //Declare a global SqlDataAdapter SqlDataAdapter 
            SqlDataAdapter SqlDataAdapter = new SqlDataAdapter();
            //Declare a global SqlCommand SqlCommand 
            SqlCommand SqlCommand = new SqlCommand();

            SqlConnection.Open();
            SqlCommand.CommandText = "Select EmployeeID,FirstName,LastName,BirthDate,City from Employees";
            SqlCommand.Connection = SqlConnection;
            SqlDataAdapter.SelectCommand = SqlCommand;
            dtTable = new DataTable();
            SqlDataAdapter.Fill(dtTable);
            ViewState.Add("WorkItemsList", dtTable);
            SqlConnection.Close();

            }
            else
            {
                dtTable = (DataTable)(ViewState["WorkItemsList"]);
            }
            //dsTemp.Tables.Add(dtTable);
            WorkItemDataRadGrid.LoadData(dtTable, "", "FirstName");
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            //if (!this.IsPostBack)
            //{
            DataSet dsQE = new DataSet();
            DataTable dtQE = new DataTable("QDataFields");
            dtQE.Columns.Add(new DataColumn("DataTypeName", System.Type.GetType("System.String")));
            dtQE.Columns.Add(new DataColumn("FieldName", System.Type.GetType("System.String")));
            dtQE.Columns.Add(new DataColumn("HideColumn", System.Type.GetType("System.Boolean")));
            dtQE.Columns.Add(new DataColumn("FieldDisplayName", System.Type.GetType("System.String")));

            DataRow drQE;

            drQE = dtQE.NewRow();
            drQE[dtQE.Columns.IndexOf("DataTypeName")] = "INT";
            drQE[dtQE.Columns.IndexOf("FieldName")] = "EmployeeeID";
            drQE[dtQE.Columns.IndexOf("HideColumn")] = "False";
            drQE[dtQE.Columns.IndexOf("FieldDisplayName")] = "EmployeeeID";
            dtQE.Rows.Add(drQE);

            drQE = dtQE.NewRow();
            drQE[dtQE.Columns.IndexOf("DataTypeName")] = "STRING";
            drQE[dtQE.Columns.IndexOf("FieldName")] = "FirstName";
            drQE[dtQE.Columns.IndexOf("HideColumn")] = "False";
            drQE[dtQE.Columns.IndexOf("FieldDisplayName")] = "First Name";
            dtQE.Rows.Add(drQE);

            drQE = dtQE.NewRow();
            drQE[dtQE.Columns.IndexOf("DataTypeName")] = "STRING";
            drQE[dtQE.Columns.IndexOf("FieldName")] = "LastName";
            drQE[dtQE.Columns.IndexOf("HideColumn")] = "False";
            drQE[dtQE.Columns.IndexOf("FieldDisplayName")] = "Last Name";
            dtQE.Rows.Add(drQE);

            drQE = dtQE.NewRow();
            drQE[dtQE.Columns.IndexOf("DataTypeName")] = "DATE";
            drQE[dtQE.Columns.IndexOf("FieldName")] = "BirthDate";
            drQE[dtQE.Columns.IndexOf("HideColumn")] = "False";
            drQE[dtQE.Columns.IndexOf("FieldDisplayName")] = "Birth Date";
            dtQE.Rows.Add(drQE);

            drQE = dtQE.NewRow();
            drQE[dtQE.Columns.IndexOf("DataTypeName")] = "STRING";
            drQE[dtQE.Columns.IndexOf("FieldName")] = "City";
            drQE[dtQE.Columns.IndexOf("HideColumn")] = "False";
            drQE[dtQE.Columns.IndexOf("FieldDisplayName")] = "City";
            dtQE.Rows.Add(drQE);

            dsQE.Tables.Add(dtQE);

            //RadAjaxManager1.AjaxSettings.AddAjaxSetting(Grid1, Grid1);
            WorkItemDataRadGrid.CreateDataGrid(dsQE);

        
            //}
           
        }

    protected void WorkItemDataRadGrid_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName == Telerik.Web.UI.RadGrid.RebindGridCommandName)
            {
                //LoadData();
                //WorkItemDataRadGrid.DataSource = dtTable;
                //if (RadGrid1.MasterTableView.IsItemInserted)
                //{
                //    e.Canceled = true;
                //}
            }
        }

    private void WorkItemDataRadGrid_SortCommand(object source, GridSortCommandEventArgs e)
        {
            WorkItemDataRadGrid.AutoGenerateColumns = false;       
            GridSortExpression sortExpr = new GridSortExpression();
            switch (e.OldSortOrder)
            {
                case GridSortOrder.None:
                   
                    WorkItemDataRadGrid.LoadData(dtTable, "", e.SortExpression + " " + "ASC");

                    break;
                case GridSortOrder.Ascending:
                   
                    WorkItemDataRadGrid.LoadData(dtTable, "", e.SortExpression + " " + "DESC");
                    break;
                case GridSortOrder.Descending:
                   
                    WorkItemDataRadGrid.LoadData(dtTable, "", e.SortExpression + " " + "ASC");
                    break;
            }

        }
    }

  21. Larry
    Larry avatar
    6 posts
    Member since:
    Oct 2010

    Posted 01 Jul 2011 Link to this post

    Sorry, I don't have time to read your code, but here's some followup on my solution to the problem...:
    (Hint: it would be more useful to attach a zipped file containing a working solution.  I dont' have time to copy/paste your files and run them)

    I opted to stop using dynamic columns.  They just ultimately cause too many problems unless you are copying Telerik's simple example exactly.  They just don't work well, IMHO.

    I changed my solution to create 20 columns at design time, and to change the Visible property on the columns that I want to display.
    I know it seems like a waste, but realize that hidden columns are not rendered on the client, I was able to solve several recurring problems in my solution that were due to dynamic columns.

    HTH


  22. Raji
    Raji avatar
    56 posts
    Member since:
    Jul 2011

    Posted 01 Jul 2011 Link to this post

    Hi Larry,

    How do I upload the .zip file. The attachment supports only image files.

  23. Gabriel
    Gabriel avatar
    33 posts
    Member since:
    Apr 2011

    Posted 16 Oct 2012 Link to this post

    I can't believe you haven't neither updated your documentation nor fixed this problem in 4 years!!!

    ¡¡TOO BAD TELERIK! I JUST LOST 5 HOURS OF MY LIFE!!
  24. Tim R
    Tim R avatar
    131 posts
    Member since:
    Feb 2006

    Posted 12 Dec 2012 Link to this post

    Telerik.Web.UI.GridColumn colSRC = new Telerik.Web.UI.GridBoundColumn();
    TodaysGrid.MasterTableView.Columns.Add(colSRC);
    colSRC.DataField = "src"; // error here
    colSRC.HeaderText = "src";

    In Visual Studio 2010, working with version 2008.1.619.20 of the Telerik RadControls for ASP.NET Ajax, the code above does not work.
    ERROR: Telerik.Web.UI.GridColumn does not contain a definition for "DataField" .

    Is this error because DataField was added in a later version of the Telerik ASP.NET controls than what we have? 


  25. Larry
    Larry avatar
    6 posts
    Member since:
    Oct 2010

    Posted 12 Dec 2012 Link to this post

    Tim,

    You need to change your declaration for the variable "colSRC".
    You've set the data type as GridColumn, which does not have a DataType field.
    You need your variable to be typed as GridBoundColumn.
    Try this:

    Telerik.Web.UI.GridBoundColumn colSRC = new Telerik.Web.UI.GridBoundColumn();
    TodaysGrid.MasterTableView.Columns.Add(colSRC);
    colSRC.DataField = "src"; // error here
    colSRC.HeaderText = "src";

  26. Tim R
    Tim R avatar
    131 posts
    Member since:
    Feb 2006

    Posted 12 Dec 2012 Link to this post

    Arrrgh.  Thanks for catching that, Larry!  
  27. Kris
    Kris avatar
    10 posts
    Member since:
    Nov 2009

    Posted 05 Mar 2013 Link to this post

    Ignore.
  28. Mark
    Mark avatar
    64 posts
    Member since:
    Nov 2009

    Posted 05 Feb 2015 Link to this post

    Columns and detail tables should be added to the corresponding collection first, before the values for their properties are set. 

    In the documentation this should be in a Caution Box.
    I have just come across this issue and is very easy to miss.
    It would also be good if there was a small example.

    As this fails
    boundColumn = new GridBoundColumn();
    boundColumn.DataField = "CustomerID";
    boundColumn.HeaderText = "CustomerID";
    RadGrid1.MasterTableView.Columns.Add(boundColumn);

    But this works.
    boundColumn = new GridBoundColumn();
    RadGrid1.MasterTableView.Columns.Add(boundColumn);
    boundColumn.DataField = "CustomerID";
    boundColumn.HeaderText = "CustomerID";
     

    This should be made more obvious! 
  29. Eyup
    Admin
    Eyup avatar
    3005 posts

    Posted 10 Feb 2015 Link to this post

    Hello Matt,

    Thank you for pointing this out. We will update the help article accordingly.

    Regards,
    Eyup
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
Back to Top
UI for ASP.NET Ajax is Ready for VS 2017