.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 exception

Posted By:      Posted Date: September 02, 2010    Points: 0   Category :ASP.Net
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

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

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

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

FileNotFound exception trying to open a site - Farm.local is Null - x64

  Hello I've created a simple asp.net application to open a site and display the title of the corresponding web. But i'm getting FileNotFoundException while trying to open the site. The same code works perfectly when i run it in a console app. My spec Windows Server 2008 R2 x64 SharePoint 2007 x64 Visual Studio 2005 My target for the asp.net app is set to 'Any CPU'. As far as permissions is considered i've checked that the current identity using which VS2005 hosts the asp.net app has full rights. In fact i've used the same identity for app pools in IIS. As an asp.net web application As a console application Any ideas? Regards NLV Visit SharePoint User group - India

Accessing a published web service gives null ref exception. Won't occur in test though?

I have an Asp.net web service that I created using Visual Studio 2005. I can acess the web service in my testenvironment, call methods and return data as expected. If this web service is published to the outside world (Outside of the company firewall), it will return a null reference exception. Does anyone have any idea why this might be happening? The same code is being used,against thesame database. The only difference is that the published website is giving back the null reference exception. If I type in the URL for the web service "https://secure.theSiteGeist.com/wsIndigo.asmx" a list of methods forthe web service is displayed in my browser. Yet if I try and call any methods on the web service I getback the null reference exception. Note that the URL I posted above is not the real name of my web service, but isjust used for reference sake.

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)  

CLR Profiler for the .NET Framework 2.0 : A bug (with possible fix!) - It throws exception - null ob

CLR Profiler for the .NET Framework 2.0   I tied to profile a service on my machine. But when I try to see the heap data (during reading of the log file) it throws exception that the object reference is not set (null object).   I debugged the CLR profiler and found that in class ReadNewLog, there is method "ReadFile" internal void ReadFile(long startFileOffset, long endFileOffset, ReadLogResult readLogResult, int requestedIndex) ...     if (matched > 0 && c != -1)     {         /* use some other stack trace as a reference */         int otherStackTraceId = ReadInt();         otherStackTraceId = stacktraceTable.MapTypeSizeStacktraceId(otherStackTraceId);         int[] stacktrace = stacktraceTable.IndexToStacktrace(otherStackTraceId);         if (matched > stacktrace.Length - hadTypeId)             matched = stacktrace.Length - hadTypeId;         for(int i = 0; i < matched; i++)         {             int funcId = stacktrace[i + hadTypeId];             Debug.Assert

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

NULL value exception when trying to save to stream


Im trying to resize an image. I have the original file and then try to resize it and save it to a new image.
However, I get an exception because the value of stream cannot be null. This makes sense, but I dont know how to prevent it:

Value cannot be null.
Parameter name: stream

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.ArgumentNullException: Value cannot be null.
Parameter name: stream

Source Error:

Line 395:
Line 396:        Dim toStream As System.IO.Stream
Line 397:        thumbnailBitmap.Save(toStream, origimage.RawFormat)
Line 398:        thumbnailGraph.Dispose()
Line 399:        thumbnailBitmap.Dispose()

Dim origimage As Image=System.Drawing.Image.FromStream(FU.PostedFile.InputStream)
        Dim thumbnailBitmap = New Bitmap(newWidth, newHeight)
        Dim t

Exception Details: System.NullReferenceException: Object reference not set to an instance of an obje


Hi, i have a Problem, i made a ASP.NET Page with VS2010 and now i want to run it on a iis6 (windows server 2003) and i get the message:

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:


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:


[NullReferenceException: Object reference not set to an instance of an object.]

   Bestellung.Bestellung.ImageButton1_Click(Object sender, ImageClickEventArgs e) in D:\foo.aspx.cs:71

   System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventArgs e) +115

   System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +120

   System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10

   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13


Null reference when using a Repeater in an UserControl



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);       &

How to avoid null pointer exception when you use invoke member in c#?

Hi ,

I am working on one of the projects where I have to use the Reflection. I have a file which has values of datatype double,string, date and time as well as empty data (null). When I import the data using invoke method, it returns the null value as one of the data in the file is empty and throws "null reference exception".
value =object.GetType().InvokeMember(string, BindingFlags.GetProperty, null, object, null);
catch {
        if (value == null) {                    
           value = null;
I catch the exception and forcefully make it null than crashing my project. When I do this, the performance of the import is very slow. The data fetch is very slow as it goes like 419  times into the catch. How to avoid this the slowness of the fetch.?  try and catch will take a lot of time in fetch as I am  catching the exception and making it null. But if I do not catch it then it will crash in the middle. I need some input on this issue. Please help me out with this.... The data fetch is perfect but it has become slow due to the try and catch..  

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.

"The located assembly's manifest definition does not match the assembly reference. (Exception from


 Since last night ive been getting this error on my website. Its happening on every page regardless of a database connection. Can anyone explain what this is and how I can fix it please?


EntityDataSource throw Exception when Update with Self-Reference


For a Table A defined in the DB like this:

A : { id, selfId, name, ... }

where selfId is a foreign key refered to Table A itself.

I generated the Entity automatically like this:

A : { string id; A self; string name, ... }

when i update the entity in gridview Edit/Update CommandField

i got the exception:

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: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be

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

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