简体   繁体   中英

ASP.NET C# Telerik RadGrid is null when using site master

I am trying to convert my current web project to utilize a site master, rather than having my navigation and headers on every individual page.

I have a RadGrid defined on a content page that uses a site.master. If I try to launch the project, it will error upon anything that tries to access a property of the RadGrid with "Object Reference not set to an instance of the object."

However, if I launch the project without using the site.master, it will load fine. There is ZERO difference in code behind the page. The only difference is the aspx front-end page using the ContentReplacer.

Here are some small snippets of what I am trying to do:

RadGrid definition within a MainContentReplacer:

                    <telerik:RadGrid runat="server" ID="RadGrid1" AllowPaging="True" PageSize="25" AllowSorting="true"
                    OnNeedDataSource="RadGrid1_NeedDataSource" OnItemDataBound="RadGrid1_ItemDataBound" AutoGenerateColumns="False"
                    AllowCustomPaging="true" PagerStyle-Mode="Advanced">
                    <ClientSettings Selecting-AllowRowSelect="True" EnablePostBackOnRowClick="true">
                    </ClientSettings>
                    <PagerStyle Mode="Slider" Position="TopAndBottom" PageSizeControlType="RadComboBox" AlwaysVisible="true"></PagerStyle>

                    <MasterTableView AllowFilteringByColumn="false" InsertItemPageIndexAction="ShowItemOnCurrentPage" CommandItemDisplay="Top" ShowHeader="true" Width="100%" DataKeyNames="ID, Location, Description, CurrentStatus, Priority, WorkOrderNumber, ReportDate, ReportedBy" AllowMultiColumnSorting="True">
                        <CommandItemSettings ShowAddNewRecordButton="false" ShowExportToCsvButton="false" ShowExportToExcelButton="false" ShowExportToPdfButton="false" ShowExportToWordButton="false" ShowRefreshButton="true" />
                        <Columns>
                            <telerik:GridBoundColumn DataField="ID" HeaderText="ID" DataType="System.Guid" FilterControlWidth="0px"></telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="Location" HeaderText="Location" DataType="System.String" FilterControlWidth="100px"></telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="Description" HeaderText="Description" DataType="System.String" FilterControlWidth="100px"></telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="CurrentStatus" HeaderText="Current Status" DataType="System.String" FilterControlWidth="100px"></telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="Priority" HeaderText="Priority" DataType="System.String" FilterControlWidth="100px"></telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="WorkOrderNumber" HeaderText="Work Order Number" DataType="System.String" FilterControlWidth="100px"></telerik:GridBoundColumn>
                            <telerik:GridDateTimeColumn DataField="ReportDate" HeaderText="Report Date" DataFormatString="{0:d}" DataType="System.DateTime" ShowFilterIcon="false" AutoPostBackOnFilter="true" FilterControlWidth="100px"></telerik:GridDateTimeColumn>
                            <telerik:GridBoundColumn DataField="ReportedBy" HeaderText="Reported By" DataType="System.String" FilterControlWidth="100px"></telerik:GridBoundColumn>
                        </Columns>
                    </MasterTableView>
                </telerik:RadGrid>

site.master:

<!DOCTYPE html>

<head runat="server">

    <telerik:RadCodeBlock ID="radCodeBlockHead" runat="server">

    <title><%=Page.Title%></title>

    <!-- // Sitewide Favicon -->
    <link rel="shortcut icon" type="image/x-icon" href="<%=Page.ResolveUrl("~")%>favicon.ico" />

    <!-- // Main Bootstrap CSS Stylesheet v3.3.4 //-->
    <link rel="stylesheet" type="text/css" href="<%=Page.ResolveUrl("~")%>includes/css/bootstrap.min.css" />   

    <!-- // Bootstrap Theme CSS Stylesheet v3.3.4 //-->
    <link rel="stylesheet" type="text/css" href="<%=Page.ResolveUrl("~")%>includes/css/bootstrap-theme.min.css" />

    <!-- // Main JQuery v1.11.2 //-->
    <script src="<%=Page.ResolveUrl("~")%>includes/js/jquery-1.11.2.min.js"></script>

    <!-- // Main Bootstrap JS v3.3.4 //-->
    <script src="<%=Page.ResolveUrl("~")%>includes/js/bootstrap.min.js"></script> 

    <!-- // Placeholder for page specific header content // -->
    <asp:ContentPlaceHolder ID="MainHeadContentReplacer" runat="server">
    </asp:ContentPlaceHolder>

</telerik:RadCodeBlock>

</head>

<body>
    <form id="form" runat="server">

    <!-- // General Telerik controls every page needs access to. // -->
    <telerik:RadScriptManager runat="server" ID="radScriptManager" />

    <div class="container-fluid">

        <telerik:RadCodeBlock ID="radCodeBlockNavigation" runat="server">

        <!-- // Main Navigation // -->
          <nav class="navbar navbar-default">
            <div class="container-fluid">
              <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                  <span class="sr-only">Toggle navigation</span>
                  <span class="icon-bar"></span>
                  <span class="icon-bar"></span>
                  <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#"><img src="<%=Page.ResolveUrl("~")%>includes/images/back.png" alt="Back" height="48" width="48" style="margin-top:-15px;" /></a>
              </div>
              <div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                  <li class="active"><a href="#"><%=Page.Title%></a></li>
                </ul>
                <ul class="nav navbar-nav navbar-right">
                  <li><a href="#"><img src="<%=Page.ResolveUrl("~")%>includes/images/home.png" alt="Back" height="48" width="48" style="margin-top:-15px;" /></a></li>
                  <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><div id="username" runat="server">USERNAME</div></a>
                    <ul class="dropdown-menu" role="menu">
                      <li class="divider"></li>
                      <li class="dropdown-header">User Commands</li>
                      <li><a href="#">Manage Profile</a></li>
                      <li><a href="#">Logout</a></li>
                    </ul>
                  </li>
                </ul>
              </div><!--/.nav-collapse -->
            </div><!--/.container-fluid -->
          </nav>

          </telerik:RadCodeBlock>

        <asp:ContentPlaceHolder ID="MainBodyContentReplacer" runat="server">

        </asp:ContentPlaceHolder>

    </div>

</form>
</body>
</html>

When the code behind gets to this specific statement:

int startIndex = (RadGrid1.CurrentPageIndex * RadGrid1.PageSize);

It errors with the above mentioned Object Reference error. The point being that the RadGrid is null. WHy is my RadGrid null when I use the site.master and works fine when I don't have the site master? I'd really like to be able to use the site master. Thanks in advance for any help or insight into my issue.

UPDATE: I'm adding more snippets of my C# Code Behind as requested below.

This is the method that gets called by whichever event is fired to requery the radgrid.

    private void LoadDataForRadGrid1()
    {
        RadGrid1.DataSource = GetWorkOrderRequests();
        RadGrid1.VirtualItemCount = getMaxRowCount();
    }

The exception occurs within GetWorkOrderRequests().

private DataTable GetWorkOrderRequests()
    {
        SqlConnection conn = new SqlConnection();
        SqlDataAdapter adapter = new SqlDataAdapter();
        SqlCommand cmd = new SqlCommand();
        SqlParameter param;
        DataTable dt = new DataTable();

        conn = FSCommon.GetFederatedConnection();

        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "usp_PM_GetWorkOrderRequests";
        cmd.Parameters.Clear();

        param = new SqlParameter();
        param.ParameterName = "@TenantID";
        param.SqlDbType = System.Data.SqlDbType.BigInt;
        param.Value = FSCommon.TenantID();
        cmd.Parameters.Add(param);

        param = new SqlParameter();
        param.ParameterName = "@Type";
        param.SqlDbType = System.Data.SqlDbType.Bit;
        param.Value = 0; // 0 is for Vesselside Requests screen. 1 is for Work Order Approval on Shoreside.
        cmd.Parameters.Add(param);

        int startIndex = (RadGrid1.CurrentPageIndex * RadGrid1.PageSize);

        param = new SqlParameter();
        param.ParameterName = "@StartIndex";
        param.SqlDbType = System.Data.SqlDbType.Int;
        param.Value = startIndex;
        cmd.Parameters.Add(param);

        param = new SqlParameter();
        param.ParameterName = "@PageSize";
        param.SqlDbType = System.Data.SqlDbType.Int;
        param.Value = RadGrid1.PageSize;
        cmd.Parameters.Add(param);

        adapter.SelectCommand = cmd;

        try
        {
            adapter.Fill(dt);
        }
        catch (Exception ex)
        {
            RenderAlert(ex.Message);
        }
        finally
        {
            conn.Dispose();
            adapter.Dispose();
        }

        return dt;
    }

UPDATE:

Adding more events that lead up to the exception.

    /// <summary>
    /// Called everytime the page is loaded and rendered on screen.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Page_PreInit();
        }

        Page_PostInit();
    }

    /// <summary>
    /// This is called when !IsPostBack on the first page load event.
    /// </summary>
    private void Page_PreInit()
    {
        LoadDataForRadGrid1();
        RadGrid1.Rebind();
    }

Based on your comment, you are calling RadGrid1 inside Page_PreInit.

RadGrid1 will always be null if you call inside Page_PreInit , because it hasn't been created yet.

The earliest you can call is inside Page_Init .

Look at ASP.NET Page Life Cycle Overview .

PreInit - Raised after the start stage is complete and before the initialization stage begins.

Init - Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.

Solution

Since you are using RadGrid , you do not have to explicit assign DataSource . Instead, assign DataSource inside RadGrid1_NeedDataSource .

RadGrid will fire NeedDataSource event automatically if it needs Data.

FYI: you should not call the DataBind() method in the NeedDataSource event. More about NeedDataSource at Telerik UI for ASP.NET AJAX Documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM