This is a migrated thread and some comments may be shown as answers.

Runtime error after binding datatable to radgrid

4 Answers 301 Views
Grid
This is a migrated thread and some comments may be shown as answers.
bogdan
Top achievements
Rank 1
bogdan asked on 09 Nov 2010, 09:54 AM
I'm binding the radgrid to a object datasource
In the select method i return a populated DataTable as seen below.
The columns are created dynamically and given a specific type because i want to use the radgrid filter.

public DataTable SelectMethod(string filterExpression, string sortExpression, string strDoctype, int maximumRows, int startRowIndex)
{
    DataTable oTable = new DataTable();
    Doctype oDoctype = new Doctype();
    bool bSuccess = true;
 
    Hashtable oInfo = new Hashtable();
    try
    {
        oDoctype = DoctypeADO.Retrieve_byDoctypeID(strDoctype);
    }
    catch
    {
        bSuccess = false;
    }
 
    if (bSuccess)
    {
        oTable.Columns.Add("DocumentID", typeof(String));
        oTable.Columns.Add("DoctypeID", typeof(String));
 
        XmlDocument oDoc = new XmlDocument();
        oDoc.LoadXml(oDoctype.DoctypeXML);
 
        foreach (XmlNode oNode in oDoc.DocumentElement)
        {
            oInfo.Add(oNode.Name, oNode.ChildNodes[0].InnerText);
        }
 
        ICollection oColl = oInfo.Keys;
        List<string> oBuilder = new List<string>();
        foreach (string strkey in oColl)
        {
            string type = string.Empty;
 
            switch (oInfo[strkey].ToString())
            {
                case "Boolean":
                    {
                        type = "Bit";
                        oTable.Columns.Add(strkey, typeof(Boolean));
                        break;
                    }
                case "Byte":
                    {
                        type = "smallint";
                        oTable.Columns.Add(strkey, typeof(Byte));
                        break;
                    }
                case "DateTime":
                    {
                        type = "datetime";
                        oTable.Columns.Add(strkey, typeof(DateTime));
                        break;
                    }
                case "Double":
                    {
                        type = "decimal";
                        oTable.Columns.Add(strkey, typeof(Double));
                        break;
                    }
                case "Int16":
                    {
                        type = "smallint";
                        oTable.Columns.Add(strkey, typeof(Int16));
                        break;
                    }
                case "Int32":
                    {
                        type = "int";
                        oTable.Columns.Add(strkey, typeof(Int32));
                        break;
                    }
                case "Single":
                    {
                        type = "decimal";
                        oTable.Columns.Add(strkey, typeof(Single));
                        break;
                    }
                case "String":
                    {
                        type = "varchar(100)";
                        oTable.Columns.Add(strkey, typeof(String));
                        break;
                    }
                default: { break; }
            }
 
            oBuilder.Add("document_xml.value('(//Fields/" + strkey + "/Value)[1]','" + type + "') as " + strkey);
        }
 
        string strQuery = @"select
                        document_id as DocumentID,
                        doctype_id as DoctypeID,
                        " + String.Join(",", oBuilder.ToArray()) +
                        @" from ( select row_number() over (order by document_id asc) as rownumber, *
                        from cs_document
                        where doctype_id = @doc_id
                        ) as test
                        where ROWNUMBER  between @nStart+1 and @nEnd";
 
        strQuery = AddFilter_Sorting(strQuery, filterExpression, sortExpression);
 
        oCommand = new SqlCommand(strQuery);
 
        oCommand.Parameters.Add(
            new SqlParameter
            {
                DbType = DbType.String,
                ParameterName = "doc_id",
                Value = strDoctype
            });
 
        oCommand.Parameters.Add(
            new SqlParameter
            {
                DbType = DbType.Int32,
                ParameterName = "nStart",
                Value = startRowIndex
            });
 
        oCommand.Parameters.Add(
            new SqlParameter
            {
                DbType = DbType.Int32,
                ParameterName = "nEnd",
                Value = startRowIndex + maximumRows
            });
 
        oCommand.Connection = oConnection;
 
        try
        {
            oConnection.Open();
            oReader = oCommand.ExecuteReader();
 
            while (oReader.Read())
            {
                object[] data = new object[oTable.Columns.Count];
 
                for (int i = 0; i < oTable.Columns.Count; i++)
                {
                    data[i] = oReader[oTable.Columns[i].ColumnName];
                }
                 
                DataRow oRow = oTable.NewRow();
                oRow.ItemArray = data;
                oTable.Rows.Add(oRow);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    return oTable;
}

protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["filterExpression"] = RadGrid1.MasterTableView.FilterExpression;
e.InputParameters["sortExpression"] = RadGrid1.MasterTableView.SortExpressions.GetSortString();
}

Here is the grid and objectdatasource from the aspx

<telerik:RadGrid ID="RadGrid1" runat="server" Width="100%" GridLines="None" AllowPaging="true"
                       AutoGenerateColumns="true" AllowFilteringByColumn="false" PageSize="10" AllowSorting="true"
                       Skin="Outlook" DataSourceID="ObjectDataSource1">
                       <MasterTableView AllowCustomSorting="true" OverrideDataSourceControlSorting="true">
                           <CommandItemSettings ExportToPdfText="Export to Pdf"></CommandItemSettings>
                           <Columns>
                               <telerik:GridTemplateColumn UniqueName="Uniq" HeaderText="Check" AllowFiltering="False">
                                   <ItemTemplate>
                                       <asp:CheckBox ID="check" runat="server" />
                                   </ItemTemplate>
                               </telerik:GridTemplateColumn>
                           </Columns>
                           <HeaderStyle VerticalAlign="Middle" />
                           <ItemStyle VerticalAlign="Middle" />
                           <FilterItemStyle VerticalAlign="Middle" />
                       </MasterTableView>
                   </telerik:RadGrid>
                   <asp:ObjectDataSource ID="ObjectDataSource1" TypeName="WebApplication1.DatabaseHandle.ObjectSource"
                       EnablePaging="true" SelectMethod="SelectMethod" SelectCountMethod="MySelectCount"
                       runat="server" OnSelecting="ObjectDataSource1_Selecting">
                       <SelectParameters>
                           <asp:Parameter Name="filterExpression" Type="String" />
                           <asp:Parameter Name="sortExpression" Type="String" />
                           <asp:ControlParameter ControlID="hidden_doctype" DbType="String" PropertyName="Value"
                               Name="strDoctype" />
                       </SelectParameters>
                   </asp:ObjectDataSource>

The problem is that when after adding a populated datetime column in the datatable it throw's me the following error at runtime :
With any other columns i have no problem.
I'm guessing it's throwing this exception when it's adding the calendar buttons in the filterzone of the grid.

The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
 
Exception Details: System.Web.HttpException: The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.
 
Source Error:
 
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
 
Stack Trace:
 
[HttpException (0x80004005): The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.]
   System.Web.UI.ControlCollection.Add(Control child) +8680983
   Telerik.Web.UI.GridDateTimeColumn.GetSharedCalendar() +192
   Telerik.Web.UI.GridDateTimeColumn.SetupFilterControls(TableCell cell) +2169
   Telerik.Web.UI.GridColumn.InitializeCell(TableCell cell, Int32 columnIndex, GridItem inItem) +5498
   Telerik.Web.UI.GridBoundColumn.InitializeCell(TableCell cell, Int32 columnIndex, GridItem inItem) +50
   Telerik.Web.UI.GridItem.Initialize(GridColumn[] columns) +142
   Telerik.Web.UI.GridItem.SetupItem(Boolean dataBind, Object dataItem, GridColumn[] columns, ControlCollection rows) +939
   Telerik.Web.UI.GridTableView.CreateFilteringItem(Boolean useDataSource, GridColumn[] copiedColumnSet, GridTHead thead) +146
   Telerik.Web.UI.GridTableView.CreateControlHierarchy(Boolean useDataSource) +1495
   Telerik.Web.UI.GridTableView.CreateChildControls(IEnumerable dataSource, Boolean useDataSource) +777
   System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +57
   System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +114
   System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +31
   System.Web.UI.WebControls.DataBoundControl.PerformSelect() +142
   Telerik.Web.UI.GridTableView.PerformSelect() +38
   System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +73
   Telerik.Web.UI.GridTableView.DataBind() +351
   System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +82
   System.Web.UI.WebControls.BaseDataBoundControl.OnPreRender(EventArgs e) +22
   Telerik.Web.UI.GridTableView.OnPreRender(EventArgs e) +57
   System.Web.UI.Control.PreRenderRecursiveInternal() +80
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842

If i set the datetime column to string per example it works perfectly.

4 Answers, 1 is accepted

Sort by
0
Accepted
Tsvetina
Telerik team
answered on 11 Nov 2010, 03:54 PM
Hi Bogdan,

What do you mean by populated GridDateTime column? When you have your RadGrid control declared in mark-up but with dynamic columns there are two main things to follow:

-all columns should be dynamically created, this means that you should not declare a template column in mark-up. Since template columns should be created on Page_Init, I advise you that you consider generating the whole RadGrid control in code-behind, or remove the template column

-there is a specific order that needs to be followed when creating the columns. You can see it in this help article.

Additionally, you could check if binding the grid to another datasource (some dummy data in NeedDataSource for example) results in the same behavior, so you can rule out the datasource as a problem if the exception keeps being thrown.

Kind regards,
Tsvetina
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
bogdan
Top achievements
Rank 1
answered on 17 Nov 2010, 09:22 AM
Changing the way the grid is populated worked.
Using the NeedDataSource solved the runtime error.

Now i'm facing a new problem.

I have the following code inside NeedDataSource
protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
       {
           RadGrid1.MasterTableView.FilterExpression = GetFilterExpression();           
           RadGrid1.DataSource = new ObjectSourceSql().SelectMethod(GetFilterExpression(), RadGrid1.MasterTableView.SortExpressions.GetSortString(), comboDocType.SelectedValue, RadGrid1.PageSize, RadGrid1.CurrentPageIndex);
           RadGrid1.MasterTableView.VirtualItemCount = new ObjectSourceSql().MySelectCount(GetFilterExpression(), RadGrid1.MasterTableView.SortExpressions.GetSortString(), comboDocType.SelectedValue);
       }

If i do not add filter the grid works perfectly , adding the correct page number count , and binding the each set of records i bring at page change based on page count and page size.
Once i add a filtering expression using the radgrid filter and try to bind in NeedDataSource the new values ( the functions return the correct page numbers and data ) the grid doesn't bind them, it show's the old values and page number.
0
Tsvetina
Telerik team
answered on 22 Nov 2010, 01:50 PM
Hi Bogdan,

Please, try changing the filter expression in the ItemCommand event handler of RadGrid in case of filtering, as shown in this help article (Example 2):
Custom option for filtering

Regards,
Tsvetina
the Telerik team
Browse the vast support resources we have to jumpstart 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.
0
bogdan
Top achievements
Rank 1
answered on 24 Nov 2010, 02:46 PM
The problem was solved by changing the EnableLinqExpressions property to "false".
Who knew that this property had impact on the filter ....
Tags
Grid
Asked by
bogdan
Top achievements
Rank 1
Answers by
Tsvetina
Telerik team
bogdan
Top achievements
Rank 1
Share this question
or