.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

Variable used before it is assigned value Null reference could

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

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

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

Comparing Null Values(from variable) in SSIS

Hi All I need to create a script that checks to see if a variable value is NULL, if it is then it executes the next SQL Task and if not then the package has finished. I have this in a SQL 2000 DTS package script: Function Main() If isnull(DTSGlobalVariables("NextLoadDate")) Then Main = DTSStepScriptResult_DontExecuteTask Else Main = DTSStepScriptResult_ExecuteTask End if End Function As you can see, all I want to do is check to see if a variable is null then don't execute the next task. But i cannot get it to work in a SQL 2005 SSIS package, so far I have created a script and come up with the following: Public Sub Main() If Dts.Variables("NextLoadDate").Value.ToString <> "" Then Dts.TaskResult = Dts.Results.Success Else Dts.TaskResult = Dts.Results.Failure End If End Sub Any Ideas? Thanks BigGopher

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

What type variable can I use to assign a possible Null or a string to?



I am converting a VB6 app to VB2008 and are having problems with replacing Variant variables.

I used Variant in cases where the data might be string or Null.

Is there a way I could check for Null and just set the string to zero lenght?

Any help would be appreciated.



Send NULL value to a stored procedure variable


Hi all. I want to send an image to a stored procedure variable that is varbinary(max) field, It works correctly when an image selected by fileupload and my image property has image file, and it can send to stored procedure. but when fileupload is empty I want to send NULL to stored procedure variable that is varbinary(max). I use DbNull.Value in C# code. But error occurs. What should I do for send Null to stored procedure? Cry

The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value t


Hi All,

        int maxAge = db.tbl_zaposlenis.Where(p => p.IdSifra == 22)
                         .Max(p => p.IdSifra);

        zaposleni.IdSifra = maxAge;

How to display the largest number in the "IdSifra?


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

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.

Dynamic Variable Names to Reference Actual set Variables


Here is an example of the concept I am used to in Coldfusion using EVALUATE and DEEVALUATE. Trying to accomplish something dynamic code side using ASP.NET C# .NET 4.0 and VS2010. The example should explain what I am trying to do... should be simple, reflaction, dynamic, eval of some kind? I thought I was close with Boolean.TryParse() but no luck even though logically it accepts a string why not convert to references variable?




bool test1 = true;

string dynboolname = "test" + 1;

if(dynboolname == true)




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

DynamicActivity cannot reference a variable defined in parent workflow


I have a custom activity that executes a workflow by creating a DynamicActivity instance that is then invoked using WorkflowInvoker.

Prior to invoking the DynamicActivity instance, I set up its Properties using a dictionary of Arguments I have populated using the DynamicArgumentDialog. One of the DynamicActivitiy properties is an out argument and I assign it an an expression that references a variable defined in the parent workflow. The intention of this is that the DynamicActivity workflow will attempt to write a result to the variable defined in the parent.

Here's the code that initialises the Proprerties collection (out arguments only):


 foreach (string argumentKey in Arguments.Keys)
    if (da.Properties.Contains(argumentKey))
     if (da.Properties[argumentKey].Type.GetGenericTypeDefinition().BaseType == typeof(OutArgument))
      da.Properties[argumentKey].Value = Arguments[argumentKey];      

   WorkflowInvoker invoker = new WorkflowInvoker(da);


where Arguments is Dictionary<string, Argument>, populated using DynamicArgumentDialog.

However, when Invoke is called I get the exception:

The following errors were encountered while processing the workflow tree:
'VisualBasicReference<Int32>': Compiler error(s) encountered

problem with SQL select statement when variable are NULL


Hello all,

I'm struggling with a strange problem.

Let me first start with giving you my SQLdatasource:


      <asp:SqlDataSource ID="SqlDataSource3" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        SelectCommand="SELECT ID_PLS, Checked, Userid, DONE, Entity, Environment, TO_DO, Description, HOW_TO, LINK_TO_PROC, Overtime, Processing_date, Driver FROM PLS_DAILY WHERE (Entity = @Entity) AND (Environment = @Environment) OR (Entity = @Entity2) AND (Environment = @Environment2)">
               <asp:SessionParameter DefaultValue="" Name="Entity" SessionField="eses_entity" 
                   Type="String" />
               <asp:SessionParameter DefaultValue="" Name="Entity2" SessionField="eb_entity" 
                   Type="String" />
               <asp:SessionParameter DefaultValue="" Name="Environment2" SessionField="eb_environment" 
                   Type="String" />
               <asp:SessionParameter DefaultValue="" Name="Environment" SessionField="eses_environment" 
                   Type="String" />

Then let me give you the sessionfield parameters:

    Protected Sub Button1_Click(ByVa

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