.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Null reference when using a Repeater in an UserControl

Posted By:      Posted Date: October 09, 2010    Points: 0   Category :ASP.Net


I get a strange null reference exception after moving my repeater from my aspx-page to an UserControl - the funny thing is that I've experienced it working and then after at while it fails - really dont see why.

Anyway....my aspx-page is pretty big so I dont want to bore you guys with all the code so here is a fragment of the code


In my aspx-page I call my UserControl like this

<%@ Register TagPrefix="UCViews" Namespace="Web.UserControls.Views" Assembly="Web" %>

<UCViews:PersonHourView ID="ucPersonHourView" runat="server" HourList='<%# hourList %>' /> 


In the aspx.cs file I make sure the hourList is always instantied

protected List<Hours> hourList = new List<Hours>();

protected override void OnInit(EventArgs e)
       base.OnInit(e);       &

View Complete Post

More Related Resource Links

Page.FindControl Causing Null Reference Exception


Hi guys,

I developed a page in VWD 2008 and it works perfectly locally, but when I deployed it on the server every Page.FindControl() call is causing the NullReference Exception "Object reference not set to an instance of an object. " Can anyone help me out? Code is below


Mike Marshall

            For i As Integer = 1 To 10
                If (CType(Page.FindControl("last_" & i), TextBox).Text.Length > 0) Or (CType(Page.FindControl("first_" & i), TextBox).Text.Length > 0) Or (CType(Page.FindControl("dob_" & i), TextBox).Text.Length > 0) Then
                    Dim person_entry(7) As String
                    person_entry(0) = info_list.Count - 1
                    person_entry(1) = CType(Page.FindControl("last_" & i), TextBox).Text
                    person_entry(2) = CType(Page.FindControl("first_" & i), TextBox).Text
                    person_entry(3) = CType(Page.FindControl("dob_" & i), TextBox).Text
                    person_entry(4) = CType(Page.FindControl("appear_" & i), TextBox).Text
                    person_entry(5) = CType(Page.FindControl("mental_" & i), TextBox).Text
                    person_entry(6) = CType(Page.FindControl("behave_" & i), TextB

Cannot access Label inside Repeater - "Object reference not set..."


I have a button on a page with a Repeater and an ObjectDataSource. To give credit where credit is due, the Repeater's paging functionality is courtesy of ScottGu. (However, I'm using ASP.NET 4.0 and SQL Server 2008, as opposed to ASP.NET 2.0 and SQL Server 2005.)

Anyway, in the button's click event, I need to access the Text property of a Label that's inside the Repeater because it's used as an input parameter in a stored procedure. I'm getting a NullReferenceException when trying to access the Label's Text property. I have researched this error and have tried a few different solutions (involving FindControl and the Repeater's ItemDataBound event), but I haven't been able to get it to work. Any suggestions, in VB or C#, would be greatly appreciated. The code is below.


<asp:Repeater ID="rptText" runat="server" DataSourceID="tbsDataSource">
<table width="100%" cellspacing="1">
<%-- some rows removed for brevity --%>

Nested controls in UserControl return null (FindControl)

Hi everyone, I have a very weird issue. I have a UserControl that has some controls inside. I want to refer those controls after, in another postback. But when I try to get them the ".Controls" property of my controls returns null. I'm working on vs2008 Here is the sample code: public partial class MyUserControl : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { foreach (Control control in this.Controls) { Response.Write(control.ClientID); } } private void MyTable() { Table table = new Table(); TableRow row = new TableRow(); TableCell cell = new TableCell(); CheckBox check = new CheckBox(); check.ID = "theId"; check.Text = "My Check"; check.AutoPostBack = true; cell.Controls.Add(check); row.Cells.Add(cell); check = new CheckBox(); check.ID = "theOther"; check.AutoPostBack = true; check.Text = "My Other Check"; cell = new TableCell(); cell.Controls.Add(check); row.Cells.Add(cell); table.Rows.Add(row); this.Controls.Add(table); } protected override void Render(HtmlTextWriter writer) { MyTable(); base.Render(writer); } } And in the Default.aspx is like:<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.cs" Inherits="Tester.Default" %> &

Null reference exception

Hi.. I'm trying to retreive values from the textboxes in the footer row of the grid view. My code is : -         con.Open();        SqlCommand com = new SqlCommand("select count(*) from prod", con);        int c = (Int32)com.ExecuteScalar();                if (c == 0)        {            DataTable dt = new DataTable();            DataColumn c1 = new DataColumn("ID");            dt.Columns.Add(c1);            DataColumn c2 = new DataColumn("DESCRIPTION");            dt.Columns.Add(c2);            DataColumn c3 = new DataColumn("QUANTITY");            dt.Columns.Add(c3);            DataColumn c4 = new DataColumn("DATE");          &nbs

Null Reference Exception was not handled by user Object Reference not set to instance of an object

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Security.Principal;using System.Data;using System.Data.SqlClient;using System.Windows;using System.Collections; public partial class Default2 : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {     }    private bool tableCopied = false;    private DataTable originalDataTable;     protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)    {         if (e.Row.RowType == DataControlRowType.DataRow)        {            //string sValue = e.Row.Cells[3].Text;             if (!tableCopied)            {                originalDataTable = ((System.Data.DataRowView)e.Row.DataItem).Row.Table.Copy();                ViewState["originalDataTable"] = originalDataTable;      &nbs

Strange Repeater Error, Object reference not set, Label not visible etc etc..

Hi Everyone,This is very strange and as of yet I cant seem to get round it, although it is a somewhat easy error to identify it is however becoming very annoying as everything I try doesn't seem to work...The repeater displays results for upcoming subscribers birthdays and after their day and month ("dd/mm/") I have a label to display the current year. This causes the old error of: Object reference not set to an instance of an object. 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.NullReferenceException: Object reference not set to an instance of an object.Source Error:  Line 55: Label lblYear = e.Item.FindControl("lblYear") as Label;Line 56: Line 57: lblYear.Text = DateTime.Now.Year.ToString();Line 58: }Line 59: As you can see the object is set correctly - The ASPX is below, for saving time on reading etc I've posted the repeater script only and not the whole page, although I can do if needs be.I've tried a number of things with subtle differences but to no avail: with Literal, same error - Tried inserting the year directly via <%#((system.datetime).now.year.tostring())%> or something to that effect, this also doesnt

Variable used before it is assigned value Null reference could

xamount is receiving this message on the last line.  The session is being set in the previous page.  Is there a way to resolve the message or should I just use a previous page postback  Dim subAmt As String = Session("MembType") Dim xamount As String Select Case subAmt Case "0" xamount = "40" Case "1" xamount = "5" Case "2" xamount = "20" Case "3" xamount = "2" End Select post_values.Add("x_amount", xamount)  

Null reference message Custom Error page

how come a Null session value that is called, doesn't get directed to the Custom Error Page?

Simple error connection string null reference

 It is failing on SqlHelper.ExecuteNonQuery(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString     public static string GetAboutMeName(string sUserID, string connectionString)        {             SqlParameter[] parameters = new SqlParameter[2];                      parameters[0] = new SqlParameter("@sUserID", SqlDbType.VarChar, 50);            parameters[0].Value = sUserID;             parameters[1] = new SqlParameter("@sResult", SqlDbType.NVarChar, 1000);            parameters[1].Direction = ParameterDirection.Output;             // Execute the stored procedure            SqlHelper.ExecuteNonQuery(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString, CommandType.StoredProcedure, "sprGetAboutMeName", parameters);         &n

Object reference not set to an instance of an object in Nested Repeater Control of CheckBox List con

 if ((item.ItemType == ListItemType.Item) || (item.ItemType == ListItemType.AlternatingItem))
                Repeater rptsub = (Repeater)item.FindControl("rptsub");
                CheckBoxList Chksub = (CheckBoxList)rptsub.FindControl("Chksub");
                Label lblsubroot = (Label)rptsub.FindControl("lblsubroot");
                DataRowView row = (DataRowView)e.Item.DataItem;
                RootId = Convert.ToInt32(row["IdApplication"].ToString());
                MetadataPermissions metadataPermissions = new MetadataPermissions(); ;
                DataSet rptRootValues = new DataSet();
                rptRootValues = metadataPermissions.GetrptSubMenus(RootId);
                DataRow[] drows = rptRootValues.Tables[0].Select("IdApplicationroot = " + row["IdApplication"].ToString());
                foreach (DataRow chkpermsns in drows)
                   ListItem li = new ListItem(chkpermsns["PermissionName"].ToString());


<asp:Repeater ID="rptroot" runat="server" OnItemDataBound="rptroot_ItemDataBound">

WebOperationContext Object reference not set to an instance of an object Null


When I try to use WebOperationContext.Current in a WCF project, the Current is null. Below is the example. Could anyone please shed a light on it?

WebForm - default.aspx:

    ServiceClient sc = new ServiceClient();

    Response.Write(sc.DoWork(1) + "<br />");

    WebOperationContext c = WebOperationContext.Current;  --Current is null

//WCF Interface

public interface IService
    int DoWork(int num);

//WCF Implementation

public class Service : IService
    public int DoWork(int num)
        return num;

System Settings: ASP.NET 3.5

Thank you in advance.

Null reference in IE8 when using jquery to create cookie


Im trying to create a cookie:

if ($.cookie('locations') == null) {
    //cookie does not exist, just set cookie to empty
    alert('cookie empty');
    $.cookie('locations', '');
    //also tried $.cookie('locations', null);

This code works in FF, but in IE8 it throws an error:
Message: '$.cookie(...)' is null or not an object

So when ($.cookie('locations') == null), I first get an alert 'cookie empty' and then the error.
How can I get this to work?

Below my code for creating a cookie:

jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        var expires = '';
        if (options.expir

Null Reference Exception while trying to initialise an Integer array


Hi ,

I am getting System.NullReferenceException:Object reference not set to an instance of an object

while executing the below code..!!

Dim arr() As Integer

Dim g,j As Integer



While g > 0
                arr(j) =0
                g = g - 1
                j = j + 1
End While

Could anybody help me out..!!!

Thanks in advance

A better way to reference your wizard steps using named steps

Note: this article uses the plain vanilla but the concepts apply equally well to its popular counterpart .

By far the most common way that I see wizard steps reference in code snippets is by their index.

Use jQuery and ASP.NET AJAX to build a client side Repeater

By sending only data to the client, you can profoundly reduce the size of what you send and see a substantial increase in performance. You also allow yourself the ability to easily add features like light-weight sorting and paging on the client. This can not only improve your users' experience, but reduce server load and bandwidth requirements.

Use jQuery and ASP.NET AJAX to build a client side Repeater

By sending only data to the client, you can profoundly reduce the size of what you send and see a substantial increase in performance. You also allow yourself the ability to easily add features like light-weight sorting and paging on the client. This can not only improve your users' experience, but reduce server load and bandwidth requirements.

To that end, I'm going to walk you through these four steps to effectively implementing a client side Repeater, using ASP.NET AJAX and jQuery:

ASP.NET Repeater Combined with jQuery FAQ Plugin Demo

The plugin is really straight forward. You just have to add your FAQ items in a header element such as an h2 and content sections in spans. This could be done in a pure HTML page or the FAQ items and content could be pulled from a database or XML file like I did in the download. Once the markup is built, the plugin does the rest. It will hide the content sections, add click events to the headers to open and close the content sections, toggle the plus/minus symbols and build the index shown on the right if you want.
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend