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

Object reference not set to an instance of an object. Error

2 Answers 1582 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Adam
Top achievements
Rank 1
Adam asked on 07 Oct 2011, 06:43 PM
We're getting this error in the prerender event of the page with a grid:

Error message: Object reference not set to an instance of an object.

Stack trace:    at Telerik.Web.UI.RadComboBox.OnInit(EventArgs e)

   at System.Web.UI.Control.InitRecursive(Control namingContainer)

   at System.Web.UI.Control.AddedControl(Control control, Int32 index)

   at Telerik.Web.UI.GridPagerItem.InitializePagerItem(GridColumn[] columns)

   at Telerik.Web.UI.GridPagerItem.SetupItem(Boolean dataBind, Object dataItem, GridColumn[] columns, ControlCollection rows)

   at Telerik.Web.UI.GridTableView.CreateTopPagerItem(Boolean useDataSource, GridColumn[] copiedColumnSet, Boolean isPagingEnabled, GridTHead thead)

   at Telerik.Web.UI.GridTableView.CreateControlHierarchy(Boolean useDataSource)

   at Telerik.Web.UI.GridTableView.CreateChildControls(IEnumerable dataSource, Boolean useDataSource)

   at System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls()

   at System.Web.UI.Control.EnsureChildControls()

   at Telerik.Web.UI.GridTableView.get_Items()

   at Telerik.Web.UI.GridTableView.GetSelectedItems()

   at XXX.StudentSearch_PreRender(Object sender, EventArgs e) in C:\XXX\StudentSearch.aspx.vb:line 140

   at System.EventHandler.Invoke(Object sender, EventArgs e)

   at System.Web.UI.Control.PreRenderRecursiveInternal()

   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)


Private Sub StudentSearch_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
        If grd.MasterTableView.GetSelectedItems.Count > 0 And grd.Visible Then
            tab.Visible = True
            mp.Visible = True
        Else
            tab.Visible = False
            mp.Visible = False
        End If
    End Sub
The error is occurring in the GetSelectedItems call. I had originally used the SelectedItems, but was getting an error with that occasionally, so I switched to GetSelectedItems. The error doesn't always happen, so it's not something I can easily reproduce.

Below is the definite for the RadGrid:
<telerik:RadGrid ID="grd" runat="server" AutoGenerateColumns="False" CellSpacing="0"
                    GridLines="None" AllowPaging="True" PageSize="20" Width="600px">
                    <ClientSettings>
                        <Selecting AllowRowSelect="False" />
                    </ClientSettings>
                    <MasterTableView HierarchyDefaultExpanded="false" HierarchyLoadMode="ServerOnDemand"
                        DataKeyNames="StudentUID">
                        <CommandItemSettings ExportToPdfText="Export to PDF"></CommandItemSettings>
                        <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column">
                            <HeaderStyle Width="20px"></HeaderStyle>
                        </RowIndicatorColumn>
                        <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column">
                            <HeaderStyle Width="20px"></HeaderStyle>
                        </ExpandCollapseColumn>
                        <Columns>
                            <telerik:GridButtonColumn CommandName="Select" FilterControlAltText="Filter column column"
                                Text="Open" UniqueName="column" ButtonType="ImageButton" ImageUrl="Images/Open.gif">
                                <ItemStyle Width="20px" />
                            </telerik:GridButtonColumn>
                            <telerik:GridBoundColumn DataField="StudentID" FilterControlAltText="Filter column1 column"
                                HeaderText="Student ID" UniqueName="column1">
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="LastName" FilterControlAltText="Filter column2 column"
                                HeaderText="Last Name" UniqueName="column2">
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="FirstName" FilterControlAltText="Filter column4 column"
                                HeaderText="First Name" UniqueName="column4">
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="Middle" FilterControlAltText="Filter column3 column"
                                HeaderText="Middle" UniqueName="column3">
                            </telerik:GridBoundColumn>
                        </Columns>
                        <EditFormSettings>
                            <EditColumn FilterControlAltText="Filter EditCommandColumn column">
                            </EditColumn>
                        </EditFormSettings>
                    </MasterTableView>
                    <FilterMenu EnableImageSprites="False">
                    </FilterMenu>
                    <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default">
                    </HeaderContextMenu>
                </telerik:RadGrid>


Iana Tsolova
Telerik team
commented on 12 Oct 2011, 03:03 PM

Hi Adam,

Can you elaborate on how is the grid bound and where are the RadTabStrip and RadMultiPage defined?

Greetings,
Iana Tsolova
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
Adam
Top achievements
Rank 1
commented on 12 Oct 2011, 05:21 PM

Below is the source of the content panel:
<h2>
        Student Search</h2>
    <telerik:RadToolBar ID="tbr" runat="server" Width="100%">
        <Items>
            <telerik:RadToolBarButton runat="server" Text="Search" Value="Search" ImageUrl="Images/find.png">
            </telerik:RadToolBarButton>
            <telerik:RadToolBarButton runat="server" Text="Clear" Value="Clear" ImageUrl="Images/clear.gif">
            </telerik:RadToolBarButton>
        </Items>
    </telerik:RadToolBar>
    <table>
        <tr>
            <td>
                Student ID:
            </td>
            <td>
                <asp:TextBox ID="txtStudentID" runat="server" Width="85px"></asp:TextBox>
            </td>
            <td>
                Last Name:
            </td>
            <td>
                <asp:TextBox ID="txtLastName" runat="server" Width="85px"></asp:TextBox>
            </td>
            <td>
                First Name:
            </td>
            <td>
                <asp:TextBox ID="txtFirstName" runat="server" Width="85px"></asp:TextBox>
            </td>
            <td>
                Middle:
            </td>
            <td>
                <asp:TextBox ID="txtMiddle" runat="server" Width="30px"></asp:TextBox>
            </td>
        </tr>
    </table>
    <table>
        <tr>
            <td valign="top">
                <telerik:RadGrid ID="grd" runat="server" AutoGenerateColumns="False" CellSpacing="0"
                    GridLines="None" AllowPaging="True" PageSize="20" Width="600px">
                    <ClientSettings>
                        <Selecting AllowRowSelect="False" />
                    </ClientSettings>
                    <MasterTableView HierarchyDefaultExpanded="false" HierarchyLoadMode="ServerOnDemand"
                        DataKeyNames="StudentUID">
                        <CommandItemSettings ExportToPdfText="Export to PDF"></CommandItemSettings>
                        <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column">
                            <HeaderStyle Width="20px"></HeaderStyle>
                        </RowIndicatorColumn>
                        <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column">
                            <HeaderStyle Width="20px"></HeaderStyle>
                        </ExpandCollapseColumn>
                        <Columns>
                            <telerik:GridButtonColumn CommandName="Select" FilterControlAltText="Filter column column"
                                Text="Open" UniqueName="column" ButtonType="ImageButton" ImageUrl="Images/Open.gif">
                                <ItemStyle Width="20px" />
                            </telerik:GridButtonColumn>
                            <telerik:GridBoundColumn DataField="StudentID" FilterControlAltText="Filter column1 column"
                                HeaderText="Student ID" UniqueName="column1">
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="LastName" FilterControlAltText="Filter column2 column"
                                HeaderText="Last Name" UniqueName="column2">
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="FirstName" FilterControlAltText="Filter column4 column"
                                HeaderText="First Name" UniqueName="column4">
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="Middle" FilterControlAltText="Filter column3 column"
                                HeaderText="Middle" UniqueName="column3">
                            </telerik:GridBoundColumn>
                        </Columns>
                        <EditFormSettings>
                            <EditColumn FilterControlAltText="Filter EditCommandColumn column">
                            </EditColumn>
                        </EditFormSettings>
                    </MasterTableView>
                    <FilterMenu EnableImageSprites="False">
                    </FilterMenu>
                    <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default">
                    </HeaderContextMenu>
                </telerik:RadGrid>
            </td>
            <td width="400px" valign="top">
                <telerik:RadTabStrip ID="tab" runat="server" MultiPageID="mp">
                    <Tabs>
                        <telerik:RadTab runat="server" Text="Info" PageViewID="Info">
                        </telerik:RadTab>
                        <telerik:RadTab runat="server" Text="Forms" PageViewID="Forms">
                        </telerik:RadTab>
                    </Tabs>
                </telerik:RadTabStrip>
                <telerik:RadMultiPage ID="mp" runat="server" BorderColor="#7E7E7E" BorderStyle="Solid" BorderWidth="1px">
                    <telerik:RadPageView ID="Info" runat="server">
                        <table>
                            <tr>
                                <td style="text-align: right; font-weight: bold">
                                    First Name:
                                </td>
                                <td>
                                    <asp:Label ID="lblFirstName" runat="server" Text=""></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: right; font-weight: bold">
                                    Last Name:
                                </td>
                                <td>
                                    <asp:Label ID="lblLastName" runat="server" Text=""></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: right; font-weight: bold">
                                    Middle:
                                </td>
                                <td>
                                    <asp:Label ID="lblMiddle" runat="server" Text=""></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: right; font-weight: bold">
                                    Student ID:
                                </td>
                                <td>
                                    <asp:Label ID="lblStudentID" runat="server" Text=""></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: right; font-weight: bold">
                                    Address:
                                </td>
                                <td>
                                    <asp:Label ID="lblAddress1" runat="server" Text=""></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                </td>
                                <td>
                                    <asp:Label ID="lblAddress2" runat="server" Text=""></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: right; font-weight: bold">
                                    City:
                                </td>
                                <td>
                                    <asp:Label ID="lblCity" runat="server" Text=""></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: right; font-weight: bold">
                                    State:
                                </td>
                                <td>
                                    <asp:Label ID="lblState" runat="server" Text=""></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: right; font-weight: bold">
                                    Zip Code:
                                </td>
                                <td>
                                    <asp:Label ID="lblZipCode" runat="server" Text=""></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: right; font-weight: bold">
                                    County:
                                </td>
                                <td>
                                    <asp:Label ID="lblCounty" runat="server" Text=""></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: right; font-weight: bold">
                                    Email:
                                </td>
                                <td>
                                    <asp:Label ID="lblEmail" runat="server" Text=""></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: right; font-weight: bold">
                                    Phone:
                                </td>
                                <td>
                                    <asp:Label ID="lblPhone" runat="server" Text=""></asp:Label>
                                </td>
                            </tr>
                             <tr>
                                <td style="text-align: right; font-weight: bold">
                                    Major:
                                </td>
                                <td>
                                    <asp:Label ID="lblMajor" runat="server" Text=""></asp:Label>
                                </td>
                            </tr>
                        </table>
                    </telerik:RadPageView>
                    <telerik:RadPageView ID="Forms" runat="server">
                        <telerik:RadTreeView ID="trvForms" runat="server">
                            <Nodes>
                                <telerik:RadTreeNode runat="server" Text="Faculty Concern Alert Forms"
                                    Value="FacultyConcernForms" PostBack="false">
                                </telerik:RadTreeNode>
                                <telerik:RadTreeNode runat="server" Text="FERPA Releases"
                                    Value="FERPAReleases" PostBack="false">
                                </telerik:RadTreeNode>
                                <telerik:RadTreeNode runat="server" Text="Medical Response Plan"
                                    Value="MedicalResponsePlan">
                                </telerik:RadTreeNode>
                                <telerik:RadTreeNode runat="server" Text="Rate My Advisor"
                                    Value="RateMyAdvisor" PostBack="false">
                                </telerik:RadTreeNode>
                                <telerik:RadTreeNode runat="server" Text="Scholarship Application"
                                    Value="ScholarshipApp">
                                </telerik:RadTreeNode>
                                <telerik:RadTreeNode runat="server" Owner="trvForms"
                                    Text="Student Accommodations" Value="StudentAccommodations">
                                </telerik:RadTreeNode>
                                <telerik:RadTreeNode runat="server"
                                    Text="Petitions for Academic Proficiency Examination" Value="ProfExamPetition">
                                </telerik:RadTreeNode>
                                <telerik:RadTreeNode runat="server"
                                    Text="Petitions for Alternative Academic Credit" Value="AltAcadCreditPetition">
                                </telerik:RadTreeNode>
                                <telerik:RadTreeNode runat="server"
                                    Text="Course Addition Requests" Value="CourseAdditionRequest">
                                </telerik:RadTreeNode>
                            </Nodes>
                        </telerik:RadTreeView>
                    </telerik:RadPageView>
                </telerik:RadMultiPage>
            </td>
        </tr>
    </table>
Adam
Top achievements
Rank 1
commented on 12 Oct 2011, 05:24 PM

As for the grid being bound, I'm using the NeedDataSource handler.
Private Sub grd_NeedDataSource(sender As Object, e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles grd.NeedDataSource
        If txtFirstName.Text = "" AndAlso txtLastName.Text = "" AndAlso txtMiddle.Text = "" AndAlso txtStudentID.Text = "" Then
            grd.DataSource = Nothing
            grd.Visible = False
        Else
            grd.Visible = True
            If IsNothing(Cache("StudentSearchResults:" & Session.SessionID)) Then
                Cache("StudentSearchResults:" & Session.SessionID) = Searcher.FindStudents(txtFirstName.Text, txtLastName.Text, txtMiddle.Text, txtStudentID.Text)
            End If
            grd.DataSource = Cache("StudentSearchResults:" & Session.SessionID)
        End If
    End Sub

Iana Tsolova
Telerik team
commented on 13 Oct 2011, 03:28 PM

Hi Adam,

Reviewing your full code I find everything properly set up. To further isolate the issue, can you specify if the error come when the grid is visible or when it is not visible and what do you have in the Cache object at that time?

Greetings,
Iana Tsolova
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
Adam
Top achievements
Rank 1
commented on 20 Oct 2011, 02:02 PM

Unfortunately, I'm unable to answer that question because I've never been able to reproduce the issue. I only see the exception after it's occurred. However, if you have a theory as to what could be happening, I'd be more than happy to force the app to behave in the manor that could make it throw the exception. i.e. make the grid not visible, etc.

Thanks,
Adam
Kevin
Top achievements
Rank 1
commented on 21 Oct 2011, 04:21 AM

I have been watching this thread waiting for answers.
I have a similar problem for a few days now, but can't find any solutions on the web. I follow the Telerik sample code from this link:

http://demos.telerik.com/aspnet-ajax/grid/examples/hierarchy/nestedviewtemplate/defaultcs.aspx


But after a exactly two successful postbacks, it starts throwing fatal error: "Object reference not set to an instance of an object", which implies the logic in code is OK, and the connections between parent and child tables are OK as well.

Please also see the attachment for the screenshot of my app, it shows two expanded child records, as soon as i try to expand the third record (third postback), it crashes with the "Object reference not set to an instance of an object" error.

Could some of the Telerik experts out there solve this problem.

Here are the page markup and code behind:

// ------------------ the page --------------------------

< %@ Page Title="" Language="C#" MasterPageFile="~/Master/LoanServ.Master" AutoEventWireup="true" CodeBehind="CustomerDashboard.aspx.cs" Inherits="LWT.LoanServ.Customers.CustomerDashboard" %>
< %@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
 
< asp:Content ID="Content1" ContentPlaceHolderID="cphHead" runat="server">
< script runat="server">
 
< /script>
< style type="text/css">
.viewWrap
{
padding: 15px;
background: #2291b5 0 0 url(Img/bluegradient.gif) repeat-x;
}
 
.contactWrap
{
padding: 10px 15px 15px 15px;
background: #fff;
color: #333;
}
 
.contactWrap td
{
padding: 0 20px 0 0;
}
 
.contactWrap td td
{
padding: 3px 20px 3px 0;
}
 
.contactWrap img
{
border: 1px solid #05679d;
}
< /style>
 
< /asp:Content>
 
 
 
< asp:Content ID="Content2" ContentPlaceHolderID="cphMain" runat="server">
 
 
< !-- content start -->
< telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
< AjaxSettings>
< telerik:AjaxSetting AjaxControlID="rgCustomer ">
< UpdatedControls>
< telerik:AjaxUpdatedControl ControlID="rgCustomer " LoadingPanelID="RadAjaxLoadingPanel1" />
< /UpdatedControls>
< /telerik:AjaxSetting>
< /AjaxSettings>
< /telerik:RadAjaxManager>
< telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" />
< telerik:RadGrid ID="rgCustomer" DataSourceID="SqlDataSource1" runat="server" Width="95%"
AutoGenerateColumns="False" PageSize="7" AllowSorting="True" AllowPaging="True"
GridLines="None" ShowStatusBar="true"
OnDetailTableDataBind="rgCustomer_DetailTableDataBind" OnItemCommand="rgCustomer_ItemCommand" OnItemCreated="rgCustomer_ItemCreated"
OnPreRender = "rgCustomer_PreRender">
 
< PagerStyle Mode="NumericPages"></PagerStyle>
 
< MasterTableView DataSourceID="SqlDataSource1" DataKeyNames="CustomerID" AllowMultiColumnSorting="True"
Width="100%">
 
< Columns>
< telerik:GridBoundColumn SortExpression="CustomerID" HeaderText="CustomerID" HeaderButtonType="TextButton"
DataField="CustomerID" Resizable="True" Reorderable="True" />
 
< telerik:GridBoundColumn SortExpression="FirstName" HeaderText="First Name" HeaderButtonType="TextButton"
DataField="FirstName" Resizable="True" Reorderable="True" />
< telerik:GridBoundColumn SortExpression="LastName" HeaderText="Last Name" HeaderButtonType="TextButton"
DataField="LastName" Resizable="True" Reorderable="True" />
< telerik:GridBoundColumn SortExpression="Email" HeaderText="Email" HeaderButtonType="TextButton"
DataField="Email" Resizable="True" Reorderable="True" />
< telerik:GridBoundColumn SortExpression="Phone" HeaderText="Phone" HeaderButtonType="TextButton"
DataField="Phone" Resizable="True" Reorderable="True" />
< telerik:GridBoundColumn SortExpression="Mobile" HeaderText="Phone" HeaderButtonType="TextButton"
DataField="Mobile" Resizable="True" Reorderable="True" />
< /Columns>
 
< NestedViewTemplate>
 
< asp:Panel runat="server" ID="pnlInnerContainer" CssClass="viewWrap" Visible="false">
< telerik:RadTabStrip runat="server" ID="TabStip1" MultiPageID="Multipage1" SelectedIndex="0">
< Tabs>
< telerik:RadTab runat="server" Text="Accounts" PageViewID="pvAccounts">
< /telerik:RadTab>
< telerik:RadTab runat="server" Text="Contact Information" PageViewID="pvContactDetails">
< /telerik:RadTab>
< telerik:RadTab runat="server" Text="Product Info" PageViewID="pvProducts">
< /telerik:RadTab>
< /Tabs>
< /telerik:RadTabStrip>
< telerik:RadMultiPage runat="server" ID="Multipage1" SelectedIndex="0" RenderSelectedPageOnly="false">
< telerik:RadPageView runat="server" ID="pvAccounts">
 
< telerik:RadGrid ID="rgAccounts" runat="server" Width="95%"
AutoGenerateColumns="False" PageSize="7" AllowSorting="True" AllowPaging="True"
GridLines="None" ShowStatusBar="true" OnItemCreated="rgAccounts_ItemCreated" OnNeedDataSource="rgAccounts_NeedDataSource" >
 
< MasterTableView DataKeyNames="AccountID" AllowMultiColumnSorting="True" Width="100%">
 
 
< Columns>
< telerik:GridBoundColumn SortExpression="AccountNumber" HeaderText="Account Number" HeaderButtonType="TextButton"
DataField="AccountNumber" Resizable="True" Reorderable="True" />
< telerik:GridBoundColumn SortExpression="SettlementDate" HeaderText="Settlement Date" HeaderButtonType="TextButton"
DataField="SettlementDate" Resizable="True" Reorderable="True" />
< telerik:GridBoundColumn SortExpression="CloseDate" HeaderText="Close Date" HeaderButtonType="TextButton"
DataField="CloseDate" Resizable="True" Reorderable="True" />
< telerik:GridBoundColumn SortExpression="AccountName" HeaderText="Account Name" HeaderButtonType="TextButton"
DataField="AccountName" Resizable="True" Reorderable="True" />
< /Columns>
 
< /MasterTableView>
< /telerik:RadGrid>
 
< /telerik:RadPageView>
< telerik:RadPageView runat="server" ID="pvContactDetails" Width="460px">
< div class="contactWrap" id="divContact">
 
 
< table cellpadding="0" cellspacing="0">
< tr>
< td>
 
< /td>
< td>
< asp:DetailsView ID="dvAddress" AllowPaging="true" GridLines="None" Width="100%"
runat="server" Font-Italic="true" AutoGenerateRows="false" OnPageIndexChanging="dvAddress_PageIndexChanging">
< Fields>
< asp:BoundField HeaderStyle-Font-Italic="false" HeaderStyle-Font-Size="Large"
HeaderText="Address Type:" DataField="AddressType" HeaderStyle-Font-Bold="true"/>
 
< asp:BoundField HeaderStyle-Font-Italic="false"
HeaderText="Address1:" DataField="Address1" HeaderStyle-Font-Bold="true"/>
< asp:BoundField HeaderText="Address2:" DataField="Address2" HeaderStyle-Font-Italic="false"
HeaderStyle-Font-Bold="true" />
< asp:BoundField HeaderText="Suburb:" DataField="Suburb" HeaderStyle-Font-Italic="false"
HeaderStyle-Font-Bold="true" />
< asp:BoundField HeaderText="State:" DataField="State" HeaderStyle-Font-Italic="false"
HeaderStyle-Font-Bold="true" />
< asp:BoundField HeaderText="Post Code:" DataField="PostCode" HeaderStyle-Font-Italic="false"
HeaderStyle-Font-Bold="true" />
< /Fields>
< /asp:DetailsView>
 
< /td>
< /tr>
< /table>
< /div>
 
< /telerik:RadPageView>
< telerik:RadPageView runat="server" ID="pvProducts" >
< telerik:RadGrid ID="rgProducts" runat="server" Width="95%"
AutoGenerateColumns="False" PageSize="7" AllowSorting="True" AllowPaging="True"
GridLines="None" ShowStatusBar="true" >
 
< MasterTableView DataKeyNames="AccountID" AllowMultiColumnSorting="True" Width="100%">
 
 
< Columns>
< telerik:GridBoundColumn SortExpression="AccountNumber" HeaderText="Account Number" HeaderButtonType="TextButton"
DataField="AccountNumber" Resizable="True" Reorderable="True" />
< telerik:GridBoundColumn SortExpression="SettlementDate" HeaderText="Settlement Date" HeaderButtonType="TextButton"
DataField="SettlementDate" Resizable="True" Reorderable="True" />
< telerik:GridBoundColumn SortExpression="CloseDate" HeaderText="Close Date" HeaderButtonType="TextButton"
DataField="CloseDate" Resizable="True" Reorderable="True" />
< telerik:GridBoundColumn SortExpression="AccountName" HeaderText="Account Name" HeaderButtonType="TextButton"
DataField="AccountName" Resizable="True" Reorderable="True" />
< /Columns>
 
< /MasterTableView>
< /telerik:RadGrid>
< /telerik:RadPageView>
 
< /telerik:RadMultiPage>
 
< /asp:Panel>
 
< /NestedViewTemplate>
 
 
 
< /MasterTableView>
< /telerik:RadGrid>
 
< asp:SqlDataSource ID="SqlDataSource1" runat="server"
SelectCommand="lmsGetCustomers" SelectCommandType="StoredProcedure" OnSelected="SqlDataSource1_Selected" >
< SelectParameters>
< asp:Parameter Name="iOrgID" Type="String" DefaultValue="" />
< asp:Parameter Name="iProfileID" Type="String" DefaultValue="" />
< /SelectParameters>
< /asp:SqlDataSource>
 
< asp:SqlDataSource ID="SqlDataSource2" runat="server"
SelectCommand="lmsGetAddressesByCustomer" SelectCommandType="StoredProcedure" OnSelected="SqlDataSource2_Selected" >
< SelectParameters>
< asp:Parameter Name="iCustomerID" Type="String" DefaultValue="7" />
< /SelectParameters>
< /asp:SqlDataSource>
< /asp:Content>



// ------------------ code behind --------------------------

 

using System;
using System.Collections.Generic;
 
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
using System.Data;
 
using LWT.Common.DAL;
using Telerik.Web.UI;
 
namespace LWT.LoanServ.Customers
{
 
public partial class CustomerDashboard : System.Web.UI.Page
{
 
 
private int _ExpandedParentId;
public int ExpandedParentId
{
get { return _ExpandedParentId; }
set { _ExpandedParentId = value; }
}
 
 
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
//rgCustomer.MasterTableView.Items[0].Expanded = true;
}
// in case nothing returned
catch (Exception ex)
{ }
}
}
 
protected void rgCustomer_PreRender(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//rgCustomer.MasterTableView.Items[0].Expanded = true;
//rgCustomer.MasterTableView.Items[0].ChildItem.FindControl("pnlInnerContainer").Visible = true;
}
}
 
protected void Page_Load(object sender, EventArgs e)
{
 
LWT.LoanServ.Master.LoanServ master = (LWT.LoanServ.Master.LoanServ)Master;
 
master.ProfileID = 1;
master.SideMenuType = LWT.LoanServ.Biz.Common.SideMenu.Customer;
 
 
string s;
s = LWTDatabase.GetInstance().GetConnectionString("LoanServ");
SqlDataSource1.ConnectionString = s;
/*
SqlDataSource1.SelectCommand = "GetAccountFacilities";
SqlDataSource1.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
*/
SqlDataSource1.SelectParameters["iOrgID"].DefaultValue = "1";
SqlDataSource1.SelectParameters["iProfileID"].DefaultValue = "1";
 
SqlDataSource2.ConnectionString = s;
//SqlDataSource2.SelectParameters["iCustomerID"].DefaultValue = "7";
 
}
 
protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
int returned = e.AffectedRows;
 
//SqlDataSource2.SelectParameters[0].DefaultValue = "985314";
 
}
 
protected void SqlDataSource2_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
int returned = e.AffectedRows;
}
 
protected void rgCustomer_ItemCommand(object source, GridCommandEventArgs e)
{
try
{
 
if (e.CommandName == RadGrid.ExpandCollapseCommandName)
{
 
RadGrid grid = (RadGrid)((GridDataItem)e.Item).ChildItem.FindControl("rgAccounts");
 
string customerIDColumn = rgCustomer.MasterTableView.DataKeyNames[0].ToString();
int customerID = LWT.Common.LWTSafeTypes.SafeInt(e.Item.OwnerTableView.Items[e.Item.ItemIndex][customerIDColumn].Text);
 
ExpandedParentId = customerID; //new Guid(e.Item.OwnerTableView.Items[e.Item.ItemIndex][customerIDColumn].Text);
 
DataSet ds = LWT.LoanServ.DAL.Customer.GetCustomerAccounts(null, customerID);
 
grid.DataSource = ds.Tables[0];
grid.DataBind();
//grid.Visible = true;
 
DetailsView detailsView = (DetailsView)((GridDataItem)e.Item).ChildItem.FindControl("dvAddress");
 
 
DataSet dsAddr = LWT.LoanServ.DAL.Customer.GetCustomerAddresses(null, customerID);
detailsView.DataSource = dsAddr.Tables[0];
detailsView.DataBind();
 
}
}
catch (Exception ex)
{
string s = ex.Message;
}
 
}
protected void rgCustomer_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridCommandItem && e.Item.OwnerTableView != rgCustomer.MasterTableView)
{
// GridCommandItem item = e.Item as GridCommandItem;
// Label label = e.Item.FindControl("ParentIdValue") as Label;
// label.Text = ExpandedParentId.ToString();
}
}
 
protected void rgAccounts_ItemCreated(object sender, GridItemEventArgs e)
{
try
{
 
RadGrid innerGrid = sender as RadGrid;
GridDataItem parentItem = (innerGrid.NamingContainer as GridNestedViewItem).ParentItem;
string s = parentItem.GetDataKeyValue("CustomerID").ToString();
 
 
innerGrid.Visible = true;
Panel pnl = innerGrid.Parent.Parent.Parent as Panel;
pnl.Visible = true;
 
}
catch (Exception ex)
{
string s = ex.Message;
}
 
}
 
protected void rgAccounts_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid innerGrid = sender as RadGrid;
GridDataItem parentItem = (innerGrid.NamingContainer as GridNestedViewItem).ParentItem;
 
}
protected void Accounts_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
string s;
s = LWTDatabase.GetInstance().GetConnectionString("LoanServ");
 
SqlDataSource2.ConnectionString = s;
SqlDataSource2.SelectCommand = "lmsGetAccountsByCustomer";
SqlDataSource2.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
SqlDataSource2.SelectParameters["iCustomerID"].DefaultValue = "1";
 
//rgCustomer.MasterTableView.DetailTables[0].DataSource = null;
 
}
 
protected void dvAddress_PageIndexChanging(Object sender, System.Web.UI.WebControls.DetailsViewPageEventArgs e)
{
//dvAddress.PageIndex = e.NewPageIndex ;
 
//dvAddress.DataSource = membersAdapter.GetMembers()
//dvAddress.DataBind();
try
{
DetailsView dv = (DetailsView)sender;
}
catch (Exception ex)
{
string s = ex.Message;
}
 
}
}
}

Iana Tsolova
Telerik team
commented on 25 Oct 2011, 02:00 PM

Hi Kevin,

The exception you receive is a server-side error. So if you disable ajax and run the page in debug mode (with F5), the application should break to the problematic line and thus you should be able to see which is the exact null object.

Kind regards,
Iana Tsolova
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
Coola
Top achievements
Rank 1
commented on 15 Dec 2011, 09:30 AM

I have similiar problem. It all started after the 2011 Q3 update.
Maria Ilieva
Telerik team
commented on 19 Dec 2011, 12:52 PM

Hello Coola,

Could you please elaborate a bit more in what scenario the mentioned error appears. Providing some part of your markup and the related code behind will help us provide more to-the-point solution.


All the best,
Maria Ilieva
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
Naresh
Top achievements
Rank 1
commented on 17 Jan 2012, 05:43 AM

it happens to me too, when a bind a radgrid after  postback, it throws the error 'Object reference not set to an instance of an object.' ...
call stack: Telerik.Web.UI.DLL!Telerik.Web.UI.RadComboBox.OnInit(..)

is it related to paging and the comboBox that show the number of results? (otherwise, not sure from where this combobox comes in my radgrid)
In this case i have only one page of data.
Maria Ilieva
Telerik team
commented on 18 Jan 2012, 03:53 PM

Hi Naresh,

As I asked several times in my posts it will be more helpful if you could provide your page markup as well as the related code behind so we could further research on the problem. The error is a generic one so without having an option to even review your code will be rather difficult to isolate the root cause of the issue.

Kind regards,
Maria Ilieva
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now

2 Answers, 1 is accepted

Sort by
0
Andrea
Top achievements
Rank 2
Iron
answered on 03 Feb 2012, 11:38 PM | edited on 01 Feb 2024, 02:49 PM

Hi,

the error seems not so generic... the problem is in the pager with a page size combobox (NextPrevAndNumeric) after a postback ... why? It's your job.

I solved forcing DataSource = "" instead the standard DataSource=Nothing if I not load a source object collection due some logics.

Best Regards

Pradeep
Top achievements
Rank 1
commented on 19 Jun 2012, 08:34 AM

Thanks Andrea,

         Your solution saved my day. Thanks alot.

Best Regards,
Pradeep Yamujala.
FvLent
Top achievements
Rank 2
commented on 02 Jul 2012, 07:34 PM

Thanks Andrea,

         Your solution saved my day as well. Thanks alot.

so the trick here is:
Instead of
grid.datasource=Nothing
just do
grid.datasource = ""
 


Best Regards,
Frank
Guy
Top achievements
Rank 1
commented on 03 Apr 2013, 10:50 PM

Thanks Andrea,

Solved my problem too ! After 4 hours of searching

Andrea
Top achievements
Rank 2
Iron
commented on 04 Apr 2013, 09:35 AM

 I am very happy that after more than a year my answer is still useful

Best Regards,

Andrea
Eren
Top achievements
Rank 1
commented on 12 Jun 2013, 08:55 PM

Thanks man! After 1,5 days at last i found this solution.
Jennifer
Top achievements
Rank 1
commented on 09 Jul 2013, 12:24 AM

Thank you! This fixed my issue as well (on exporting to Excel!)
Richy
Top achievements
Rank 1
commented on 13 Jan 2014, 10:39 AM

Thanks Andrea,

I upgraded from 2011 Q1 to 2013 Q3, and pages that were previously working were falling over. I couldn't figure out what was happening. I started to re-piece my AJAX logic step by step but couldn't isolate the reason for the error.


I do find it hard to believe that 12 months and 3 releases later that this issue hasn't been fixed by Telerik. Very disappointing.
Maria Ilieva
Telerik team
commented on 14 Jan 2014, 12:08 PM

Hello Richy,

Could you please elaborate what are the exact issues you are facing after the upgrade? The upgrade you have performed is rather big and a lot of changes and new features and functionality are implemented during this period. Therefore providing the explanation of the exact issue you are facing and the error you are currently getting will help us point you to the right direction in fixing the problem. 

Regards,
Maria Ilieva
Telerik
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to the blog feed now.
usman
Top achievements
Rank 1
commented on 30 Jun 2014, 05:41 AM

Thanks Andrea,
since 1.5 days I was facing this problem and you saved my life.

Kelsey
Top achievements
Rank 1
commented on 02 Mar 2015, 08:53 PM

What Andrea said solved the issue for me.

I just placed it inside of the RadGrid's DataBind handler
if (RadGrid == null)   //By the end of the DataBind function
    RadGrid.DataSource  = ""   
Kelsey
Top achievements
Rank 1
commented on 02 Mar 2015, 08:54 PM

Andreas solution solved it for me as well.
0
Attila Antal
Telerik team
answered on 01 Feb 2024, 04:59 PM

For anyone else who is experiencing this issue, please hear me out.

Setting the Grid's data source to "null" / "Nothing" in the NeedDataSource event is not the correct approach and has never been.  

The Grid relies on the column structure/schema for multiple reasons, so the data source you assign to it must contain the structure (whether or not it's empty).

One good reason is when the "AutoGenerateColumns" is set to "True" the columns are generated automatically. That cannot happen without a data source that contains the necessary schema/structure.

<telerik:RadGrid ID="RadGrid1" runat="server" OnNeedDataSource="RadGrid1_NeedDataSource">
    <MasterTableView AutoGenerateColumns="True">
    </MasterTableView>
</telerik:RadGrid>

In this case, setting "null" as the data source will not render the Grid structure at all. All you will see is the borders of the Grid element.

Example screenshot

Assigning an empty data source that has structure will render the Grid, the columns and show the "No records to display"

Example screenshot

 

Correct approach

Within the NeedDataSource event, if you want to set an "EMPTY" data source to the Grid, make sure the data source itself contains the structure.

Example using an empty DataTable object for this specific structure

C#

protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
    RadGrid grid = (RadGrid) sender;

    DataTable dt = new DataTable();

    dt.Columns.Add("OrderID", typeof(int));
    dt.Columns.Add("ShipName", typeof(string));

    dt.Rows.Add(1, "Name 1");
    dt.Rows.Add(2, "Name 2");
    dt.Rows.Add(3, "Name 3");

    if (true)
    {
        // data source with records
        grid.DataSource = dt;
    }
    else
    {
        // empty data source - Clone() copies only the DataTable's structure
        grid.DataSource = dt.Clone();
    }
}

VB

Protected Sub RadGrid1_NeedDataSource(ByVal sender As Object, ByVal e As GridNeedDataSourceEventArgs)
    Dim grid As RadGrid = CType(sender, RadGrid)
    Dim dt As DataTable = New DataTable()
    dt.Columns.Add("OrderID", GetType(Integer))
    dt.Columns.Add("ShipName", GetType(String))
    dt.Rows.Add(1, "Name 1")
    dt.Rows.Add(2, "Name 2")
    dt.Rows.Add(3, "Name 3")

    If True Then
        'data source with records
        grid.DataSource = dt
    Else
        'empty data source - Clone() copies only the DataTable's structure
        grid.DataSource = dt.Clone()
    End If
End Sub

 

Example using an empty Custom object for this specific structure

C#

protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
    RadGrid grid = (RadGrid) sender;

    List<MyCustomObject> myList = new List<MyCustomObject>();

    myList.Add(new MyCustomObject() { OrderID = 1, ShipName = "Name 1" });
    myList.Add(new MyCustomObject() { OrderID = 2, ShipName = "Name 2" });
    myList.Add(new MyCustomObject() { OrderID = 3, ShipName = "Name 3" });

    if (true)
    {
        grid.DataSource = myList;
    }else
    {
        grid.DataSource = new List<MyCustomObject>();
    }
}

VB

Protected Sub RadGrid1_NeedDataSource(ByVal sender As Object, ByVal e As GridNeedDataSourceEventArgs)
    Dim grid As RadGrid = CType(sender, RadGrid)
    Dim myList As List(Of MyCustomObject) = New List(Of MyCustomObject)()
    myList.Add(New MyCustomObject() With {
        .OrderID = 1,
        .ShipName = "Name 1"
    })
    myList.Add(New MyCustomObject() With {
        .OrderID = 2,
        .ShipName = "Name 2"
    })
    myList.Add(New MyCustomObject() With {
        .OrderID = 3,
        .ShipName = "Name 3"
    })

    If True Then
        grid.DataSource = myList
    Else
        grid.DataSource = New List(Of MyCustomObject)()
    End If
End Sub

If the issue appears with this approach, then we can consider it a bug and assign the developers to investigate it. 

Regards,
Attila Antal
Progress Telerik

Stay tuned by visiting our public roadmap and feedback portal pages! Or perhaps, if you are new to our Telerik family, check out our getting started resources
Andrea
Top achievements
Rank 2
Iron
commented on 01 Feb 2024, 05:18 PM

I apologize, I simply corrected a typo in an old comment of mine, the new forum has done the magic..... and the rest is history.  

I think that in 2024 no one is still facing this problem.

 

Sorry

 

Attila Antal
Telerik team
commented on 02 Feb 2024, 11:13 AM

It's alright Andrea, do not feel bad.

This Forum post popped up in our System and thought I would clarify the correct approach in case anyone else experiences the same issue or even other issues that are caused by setting the Grid's data source to "null" just to clear the data source (e.g. provide and empty source).

 

Tags
Grid
Asked by
Adam
Top achievements
Rank 1
Answers by
Andrea
Top achievements
Rank 2
Iron
Attila Antal
Telerik team
Share this question
or