Showing posts with label reference. Show all posts
Showing posts with label reference. Show all posts

Thursday, March 29, 2012

Object Null Reference Exception (vb)

Can someone tell me what this compiler error means?
Using VS.NET 2002/VB

----------------
Dim objFIF As New RMClassLib.FtInFr()

objFIF.CreateNewFIF(False, False, 3, 24)

pitchInDrp.DataSource = objFIF.GetNewFIF

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

Line 133: Dim objFIF As New RMClassLib.FtInFr()
-----------------

Thanks,
GeorgeIgnore that request for help. I think I have it figured out.

Thanks.
George

"George" <--@.--.--> wrote in message
news:4L0Sb.30723$6O4.823971@.bgtnsc04-news.ops.worldnet.att.net...
> Can someone tell me what this compiler error means?
> Using VS.NET 2002/VB
> ----------------
> Dim objFIF As New RMClassLib.FtInFr()
> objFIF.CreateNewFIF(False, False, 3, 24)
> pitchInDrp.DataSource = objFIF.GetNewFIF
> Exception Details: System.NullReferenceException: Object reference not set
> to an instance of an object.
> Line 133: Dim objFIF As New RMClassLib.FtInFr()
> -----------------
> Thanks,
> George

Object reference

The error is:
Object reference not set to an instance of an object. (See commented line below---)
I tried using the new keyword and that does not solve the problem.
Do you see the problem?

Private Sub LoadData(ByVal SortKey As String)

Dim strPath As String = Server.MapPath(Request.ApplicationPath)
Dim ds As New DataSet()
ds.ReadXmlSchema(strPath & "\XML\A.xsd")
ds.ReadXml(strPath & "\XML\A.xml")

'------This line gives the error------------
Dim view As DataView = ds.Tables("Orders").DefaultView
'------------------
If Not (SortKey Is Nothing) And SortKey <> [String].Empty Then
view.Sort = SortKey
End If
dgUsers.DataSource = view
dgUsers.DataBind()
End SubOne problem i see is that you never name a table "Orders" but try to reference it anyway. If you only have one table try referencing ds.Tables(0).DefaultView. Or, ds.Table(0).TableName = "Orders" then use ds.Tables("Orders").DefaultView.

Object Reference

I am having a very strange problem with my asp.net application. I am
getting error: 'Object reference not set to an instance of an object' when I
run my app from my hosting company. I have installed my application on
three different machines (including a brand new install of winxp, vs2003) at
our offices and everything seems to work fine. What could be wrong with the
server at hosting company. When i speak to them about the problem they
point the finger at my script, which I think is not a problem because it
works fine everytime I install it. I really need help with this problem.
Thanks.
ArbenHello Arapi,
Though the problem you have written may have number of reasons, but i feel
like that there is something which you make a reference on your development
machine is not present on the host machine.
Check out all the references you made, there respective dll;s are present as
well as in the hosting machine.
Wajahat Abbas
http://www.wajahatabbas.com
http://www.dotnetpakistan.com
"Arapi" wrote:

> I am having a very strange problem with my asp.net application. I am
> getting error: 'Object reference not set to an instance of an object' when
I
> run my app from my hosting company. I have installed my application on
> three different machines (including a brand new install of winxp, vs2003)
at
> our offices and everything seems to work fine. What could be wrong with t
he
> server at hosting company. When i speak to them about the problem they
> point the finger at my script, which I think is not a problem because it
> works fine everytime I install it. I really need help with this problem.
> Thanks.
> Arben
>
>
Hi Wajahat,
Thank you for your response. The way I do my deployment is: copy all the
contents of the bin folder to the bin folder on the hosting machine, and
aspx files to their respective folders.
I just dont understand that if my application works in three different
machines with default installation (no customized installations whatsoever)
why I am getting this error on the host machine?
"Wajahat Abbas" <wajahatabbas@.yahoo.com> wrote in message
news:DF2E7E87-9B3A-41D6-BA78-42226C2C5752@.microsoft.com...
> Hello Arapi,
> Though the problem you have written may have number of reasons, but i feel
> like that there is something which you make a reference on your
> development
> machine is not present on the host machine.
> Check out all the references you made, there respective dll;s are present
> as
> well as in the hosting machine.
> --
> Wajahat Abbas
> http://www.wajahatabbas.com
> http://www.dotnetpakistan.com
>
>
> "Arapi" wrote:
>
You are counting for certain objects to be present but they are not. Whether
it because they don't exist on the host machine, like the other poster
suggested, or you might lack necessary permission for using them. The bottom
line there is something in the program that is supposed to instantiate an
object and this doesn't happen.
Eliyahu
"Arapi" <aarapi@.gmail.com> wrote in message
news:%23VOk51duFHA.3424@.tk2msftngp13.phx.gbl...
> Hi Wajahat,
> Thank you for your response. The way I do my deployment is: copy all the
> contents of the bin folder to the bin folder on the hosting machine, and
> aspx files to their respective folders.
> I just dont understand that if my application works in three different
> machines with default installation (no customized installations
whatsoever)
> why I am getting this error on the host machine?
> "Wajahat Abbas" <wajahatabbas@.yahoo.com> wrote in message
> news:DF2E7E87-9B3A-41D6-BA78-42226C2C5752@.microsoft.com...
feel
present
vs2003)
with
it
problem.
>
> What could be wrong with the server at hosting company. When i speak to
> them about the problem they point the finger at my script, which I think
> is not a problem because it works fine everytime I install it. I really
> need help with this problem.
Do you program with that logic? You don't know where it's been! ;-)
Let me explain, if I may. You say you're getting an exception: "Object
reference not set to an instance of an object." This exception means that
some code in your app is referencing an object which does not exist. For
example, you create a variable, using a method, which returns null
(Nothing), and then, without checking to see whether it is nothing, you
attempt to use it as if it were the object you expect it to be.
Now, you posted no other information about this exception, such as where in
your application it occurred, which can be obtained from the Exception
thrown, using a Stack Trace. This is the first step to diagnosing your
problem. You need to identify the page that contained the line in your code
that threw the exception, and the line of code itself. Next, you need to
identify the object references in that line of code, and work backwards from
each one, identifying what operation(s) might cause that object reference to
be null (Nothing). The easiest way to do this is to implement structured
exception handling (Try/Catch), and using whatever means you choose to pass
the exception information to you, such as logging it, writing it to a file,
or displaying it in the page (which may be the only possible method on a
hosted web site, depending on your permissions).
Knowing what operation caused the object reference to be null (Nothing) will
determine the cause of the issue, and more importantly, what you need to do
to prevent it.
Assuming with no information that the fault somehow lies with your hosting
service environment, simply because you haven't managed to reproduce it on
your local development machine is a gigantic leap of illogical assumption!
HTH,
Kevin Spencer
Microsoft MVP
.Net Developer
Neither a follower nor a lender be.
"Arapi" <aarapi@.gmail.com> wrote in message
news:%23HSKidduFHA.2076@.TK2MSFTNGP14.phx.gbl...
>I am having a very strange problem with my asp.net application. I am
>getting error: 'Object reference not set to an instance of an object' when
>I run my app from my hosting company. I have installed my application on
>three different machines (including a brand new install of winxp, vs2003)
>at our offices and everything seems to work fine. What could be wrong with
>the server at hosting company. When i speak to them about the problem they
>point the finger at my script, which I think is not a problem because it
>works fine everytime I install it. I really need help with this problem.
>Thanks.
> Arben
>

Object reference

I get an error message:
Exception Details: System.NullReferenceException: Object reference not set
to an instance of an object.

I get an error in line:
If Session("user") Is Nothing Then...

What could be wrong?Apparently, the Session doesn't exist in the context of the line you posted.

--
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.

"simon" <simon.zupan@.stud-moderna.si> wrote in message
news:e4bE4IDtDHA.2148@.TK2MSFTNGP12.phx.gbl...
> I get an error message:
> Exception Details: System.NullReferenceException: Object reference not set
> to an instance of an object.
> I get an error in line:
> If Session("user") Is Nothing Then...
> What could be wrong?
>
>
Hi,

> I get an error in line:
> If Session("user") Is Nothing Then...
> What could be wrong?

Session object is null (Nothing).

1) Check <sessionState> element in your Web.config file.
2) Make sure that you retrieve it correctly.

--
______________________________
With best wishes, Arthur Nesterovsky
Please visit my home page:
http://www.nesterovsky-bros.com
Hi,

If I use session object in user control(aspx page), it doesn't work.
If I write the same code in default.aspx then everything is fine.

In past I have code and all my functions in include.asp page, which I
included on all my pages.
I had line:
If Session("user") Is Nothing Then
response.redirect "login.asp"
End If

Now I move all my functions to user control (by the book) and register it on
all my pages - approximate the similar like with include.
But if the session won't work, I don't want to write line with session
checking on all my pages.
Should I use include statement(which is past from asp) or is there some
other way?

Thank you,
Simon

"Arthur Nesterovsky" <arthur_NO_SPAM_PLEASE_@.nesterovsky-bros.com> wrote in
message news:uHYr6XDtDHA.1876@.TK2MSFTNGP09.phx.gbl...
> Hi,
> > I get an error in line:
> > If Session("user") Is Nothing Then...
> > What could be wrong?
> Session object is null (Nothing).
> 1) Check <sessionState> element in your Web.config file.
> 2) Make sure that you retrieve it correctly.
> --
> ______________________________
> With best wishes, Arthur Nesterovsky
> Please visit my home page:
> http://www.nesterovsky-bros.com
Hi,

> I had line:
> If Session("user") Is Nothing Then
> response.redirect "login.asp"
> End If
> Now I move all my functions to user control (by the book) and register it
on
> all my pages - approximate the similar like with include.

Try to check

HttpContext.Current.Session("user") instead.

--
______________________________
With best wishes, Arthur Nesterovsky
Please visit my home page:
http://www.nesterovsky-bros.com
I have control leviMenu.ascx, where I define session:
If HttpContext.Current.Session("user") Is Nothing Then
Dim uporabnik(2)
uporabnik(0) = "1"
uporabnik(1) = "Simon Zupan"
uporabnik(2) = "2"
Session("user") = uporabnik
End If

Then I register it on the page:

<%@. Register TagPrefix ="Menu" TagName = "LeviMenu" Src =
"userControls\leviMenu.ascx"%
then use it on page:

<menu:leviMenu runat="server" ID="Levimenu1"></menu:leviMenu
Then on the same page in Private Sub Page_Load event, I'm reading the value
from session:

HttpContext.Current.Session("user")(0)

And I gett an error message:

System.NullReferenceException: Object variable or With block variable not
set.

The session object is not recognized.

How can I solve this problem?

I have session object in user control because it's registered on all pages.
I can write the session code on each page separeted, it works than, but than
I don't have the code on one place, it doesn't make any sence.

Thank you,
Simon

"Arthur Nesterovsky" <arthur_NO_SPAM_PLEASE_@.nesterovsky-bros.com> wrote in
message news:Oz3PxfMtDHA.1756@.TK2MSFTNGP09.phx.gbl...
> Hi,
> > I had line:
> > If Session("user") Is Nothing Then
> > response.redirect "login.asp"
> > End If
> > Now I move all my functions to user control (by the book) and register
it
> on
> > all my pages - approximate the similar like with include.
> Try to check
> HttpContext.Current.Session("user") instead.
> --
> ______________________________
> With best wishes, Arthur Nesterovsky
> Please visit my home page:
> http://www.nesterovsky-bros.com

Object Reference

I am having a very strange problem with my asp.net application. I am
getting error: 'Object reference not set to an instance of an object' when I
run my app from my hosting company. I have installed my application on
three different machines (including a brand new install of winxp, vs2003) at
our offices and everything seems to work fine. What could be wrong with the
server at hosting company. When i speak to them about the problem they
point the finger at my script, which I think is not a problem because it
works fine everytime I install it. I really need help with this problem.
Thanks.

ArbenHello Arapi,

Though the problem you have written may have number of reasons, but i feel
like that there is something which you make a reference on your development
machine is not present on the host machine.

Check out all the references you made, there respective dll;s are present as
well as in the hosting machine.

--
Wajahat Abbas

http://www.wajahatabbas.com
http://www.dotnetpakistan.com

"Arapi" wrote:

> I am having a very strange problem with my asp.net application. I am
> getting error: 'Object reference not set to an instance of an object' when I
> run my app from my hosting company. I have installed my application on
> three different machines (including a brand new install of winxp, vs2003) at
> our offices and everything seems to work fine. What could be wrong with the
> server at hosting company. When i speak to them about the problem they
> point the finger at my script, which I think is not a problem because it
> works fine everytime I install it. I really need help with this problem.
> Thanks.
> Arben
>
Hi Wajahat,
Thank you for your response. The way I do my deployment is: copy all the
contents of the bin folder to the bin folder on the hosting machine, and
aspx files to their respective folders.
I just dont understand that if my application works in three different
machines with default installation (no customized installations whatsoever)
why I am getting this error on the host machine?

"Wajahat Abbas" <wajahatabbas@.yahoo.com> wrote in message
news:DF2E7E87-9B3A-41D6-BA78-42226C2C5752@.microsoft.com...
> Hello Arapi,
> Though the problem you have written may have number of reasons, but i feel
> like that there is something which you make a reference on your
> development
> machine is not present on the host machine.
> Check out all the references you made, there respective dll;s are present
> as
> well as in the hosting machine.
> --
> Wajahat Abbas
> http://www.wajahatabbas.com
> http://www.dotnetpakistan.com
>
>
> "Arapi" wrote:
>> I am having a very strange problem with my asp.net application. I am
>> getting error: 'Object reference not set to an instance of an object'
>> when I
>> run my app from my hosting company. I have installed my application on
>> three different machines (including a brand new install of winxp, vs2003)
>> at
>> our offices and everything seems to work fine. What could be wrong with
>> the
>> server at hosting company. When i speak to them about the problem they
>> point the finger at my script, which I think is not a problem because it
>> works fine everytime I install it. I really need help with this problem.
>> Thanks.
>>
>> Arben
>>
>>
>
You are counting for certain objects to be present but they are not. Whether
it because they don't exist on the host machine, like the other poster
suggested, or you might lack necessary permission for using them. The bottom
line there is something in the program that is supposed to instantiate an
object and this doesn't happen.

Eliyahu

"Arapi" <aarapi@.gmail.com> wrote in message
news:%23VOk51duFHA.3424@.tk2msftngp13.phx.gbl...
> Hi Wajahat,
> Thank you for your response. The way I do my deployment is: copy all the
> contents of the bin folder to the bin folder on the hosting machine, and
> aspx files to their respective folders.
> I just dont understand that if my application works in three different
> machines with default installation (no customized installations
whatsoever)
> why I am getting this error on the host machine?
> "Wajahat Abbas" <wajahatabbas@.yahoo.com> wrote in message
> news:DF2E7E87-9B3A-41D6-BA78-42226C2C5752@.microsoft.com...
> > Hello Arapi,
> > Though the problem you have written may have number of reasons, but i
feel
> > like that there is something which you make a reference on your
> > development
> > machine is not present on the host machine.
> > Check out all the references you made, there respective dll;s are
present
> > as
> > well as in the hosting machine.
> > --
> > Wajahat Abbas
> > http://www.wajahatabbas.com
> > http://www.dotnetpakistan.com
> > "Arapi" wrote:
> >> I am having a very strange problem with my asp.net application. I am
> >> getting error: 'Object reference not set to an instance of an object'
> >> when I
> >> run my app from my hosting company. I have installed my application on
> >> three different machines (including a brand new install of winxp,
vs2003)
> >> at
> >> our offices and everything seems to work fine. What could be wrong
with
> >> the
> >> server at hosting company. When i speak to them about the problem they
> >> point the finger at my script, which I think is not a problem because
it
> >> works fine everytime I install it. I really need help with this
problem.
> >> Thanks.
> >>
> >> Arben
> >>
> >>
> >>
> What could be wrong with the server at hosting company. When i speak to
> them about the problem they point the finger at my script, which I think
> is not a problem because it works fine everytime I install it. I really
> need help with this problem.

Do you program with that logic? You don't know where it's been! ;-)

Let me explain, if I may. You say you're getting an exception: "Object
reference not set to an instance of an object." This exception means that
some code in your app is referencing an object which does not exist. For
example, you create a variable, using a method, which returns null
(Nothing), and then, without checking to see whether it is nothing, you
attempt to use it as if it were the object you expect it to be.

Now, you posted no other information about this exception, such as where in
your application it occurred, which can be obtained from the Exception
thrown, using a Stack Trace. This is the first step to diagnosing your
problem. You need to identify the page that contained the line in your code
that threw the exception, and the line of code itself. Next, you need to
identify the object references in that line of code, and work backwards from
each one, identifying what operation(s) might cause that object reference to
be null (Nothing). The easiest way to do this is to implement structured
exception handling (Try/Catch), and using whatever means you choose to pass
the exception information to you, such as logging it, writing it to a file,
or displaying it in the page (which may be the only possible method on a
hosted web site, depending on your permissions).

Knowing what operation caused the object reference to be null (Nothing) will
determine the cause of the issue, and more importantly, what you need to do
to prevent it.

Assuming with no information that the fault somehow lies with your hosting
service environment, simply because you haven't managed to reproduce it on
your local development machine is a gigantic leap of illogical assumption!

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Neither a follower nor a lender be.

"Arapi" <aarapi@.gmail.com> wrote in message
news:%23HSKidduFHA.2076@.TK2MSFTNGP14.phx.gbl...
>I am having a very strange problem with my asp.net application. I am
>getting error: 'Object reference not set to an instance of an object' when
>I run my app from my hosting company. I have installed my application on
>three different machines (including a brand new install of winxp, vs2003)
>at our offices and everything seems to work fine. What could be wrong with
>the server at hosting company. When i speak to them about the problem they
>point the finger at my script, which I think is not a problem because it
>works fine everytime I install it. I really need help with this problem.
>Thanks.
> Arben

object reference a mystery

Hi

Im busy building a class where i want the class members to have access to and be able to manipulate items on a web page.
Surely if i declare an instance of my page class (MyPage_Default) in this new class then i should have access to its members?

Could somebody please have a look at my code and tell me what i could be doing wrong?
thanks

Here is the code: (first my new class and then code for my page's code behind)

public class wizard

{

public int myNumber;

public void SetMyNumber(int newNumber)

{

myNumber = newNumber;

}

public void work()

{

MyPage_Default i = new MyPage_Default();

i.label("hello");

}

}

public partial class MyPage_Default : System.Web.UI.Page

{

wizard w = new wizard();

protected void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack)

{

w.SetMyNumber(10);

}

w.work();

}

protected void btnNext_Click(object sender, EventArgs e)

{

w.SetMyNumber(30);

w.work();

}

public void PageDo()

{

Label1.Text = w.myNumber.ToString();

}

public void label(string newValue)

{

Label1.Text = newValue;

}

}

Hi,

there are several solutions to this. 2 that pop up in my mind are these:

1<%@. Page Language="C#" %>23<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">45<script runat="server">67 protected void Page_Load(object sender, EventArgs e)8 {9 ContextTest.SetNumber(13);10 ContextTest.SetNumberTry2(Label2, 8);11 }1213</script>1415<html xmlns="http://www.w3.org/1999/xhtml">16<head runat="server">17 <title>Untitled Page</title>18</head>19<body>20 <form id="form1" runat="server">21 <div>22 <asp:Label ID="Label1" runat="server"></asp:Label>23 <asp:Label ID="Label2" runat="server"></asp:Label>24 </div>25 </form>26</body>27</html>

and in the App_Code subfolder I put this class:

1using System;2using System.Data;3using System.Configuration;4using System.Web;5using System.Web.Security;6using System.Web.UI;7using System.Web.UI.WebControls;8using System.Web.UI.WebControls.WebParts;9using System.Web.UI.HtmlControls;1011/// <summary>12/// Summary description for ContextTest13/// </summary>14public class ContextTest15{16public static void SetNumber(int number)17 {18 ((Label)((Page)HttpContext.Current.CurrentHandler).FindControl("Label1")).Text = number.ToString();19 }2021public static void SetNumberTry2(Label control,int number)22 {23 control.Text = number.ToString();24 }25}

As you can see, you don't need to instantiate another object of the type of your particular class. In the SetNumber method I just pass an integer and in the method I get the CurrentHandler, which is the page, that runs in the current context. After casting you can use the FindControl method to find the Label1 and set its text.

In SetNumberTry2 however I just pass the Label2 control directly, which references the instance of the Label2 control, and set its Text property directly to the number.

Grz, Kris.


Hi Kris.

Thanks for your quick reply.


For some reason the first method doesn't work :( It gies me the same error. (Object reference...)
The second however does.

Once again thanks a mil! This will definitely be very useful in time to come
gem-code!


Hi,

Dewald:

For some reason the first method doesn't work :( It gies me the same error. (Object reference...)

can you provide the error you're getting? Did you put the class in the App_Code subfolder or not?

Grz, Kris.


Hi again!

Nah the code is def in the App_Code folder.

This is how i implement it:
//Show the current step. Assign to some label specified
public void ShowStep()
{
//control.Text = WizardCurStep.ToString();
((Label)((Page)HttpContext.Current.CurrentHandler).FindControl("Label1")).Text = WizardCurStep.ToString();
}

WizardCurStep is defined up in the same page as int

Here is the error im getting:

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 47: {Line 48: //control.Text = WizardCurStep.ToString();Line 49: ((Label)((Page)HttpContext.Current.CurrentHandler).FindControl("Label1")).Text = WizardCurStep.ToString();Line 50: }Line 51:


Dewald:

WizardCurStep is defined up in the same page as int

In the page but you don't pass it as an input parameter to your method in the custom class.

Grz, Kris.


Hi.

I'm trying to seperate the values used by the wizard class from the actual page that uses the wizard. Therefore ive declare several integers in the seperate class so that it can keep track of those values itself.
(Instead of having to assign values to viewstate or some label etc)

public class wizard
{
private int WizardMinStep;
private int WizardMaxStep;
private int WizardCurStep;

// Class Contructor
public wizard(int MinStep, int MaxStep)
{
WizardMinStep = MinStep;
WizardMaxStep = MaxStep;
}

//Step Forward
public void StepForward(Button control)
{
if (WizardCurStep >= WizardMaxStep)
{
control.Enabled = false;
}
else
{
WizardCurStep++;
control.Enabled = true;
}

//Show the current step. Assign to some label specified
public void ShowStep(Label control)
{
control.Text = WizardCurStep.ToString();
}

}

I wont be able to pass these values to the methods from the page without the page 'knowning' what they are.
Surely this is the same as you suggested?


Ok so ive given this a serious go now.
Actually my logic seem to work just fine. The code does increment the value set at the top of the page when i click my forward button and the "StepForward()" method is called. Only one problem now...
When i click the forward button for the second time... it doesn't increment that value again to 3. It just stays there on 2. (I pass to the class constructor the innitial value to 1)
Since VS doesn't want to break into debugger so i can step through the code i have to assume that the variable is stuck in some way.

I use the word 'stuck' because the value isn't incremeted beyond 2, however once i call the "StepPrevious()" method the value is decremented back to 1.
So it isn't a case of either loosing the value or it being set back to the innitial value of 1 with every server round trip. (If it was reset during server round trip the value would have been 0)

Kris would you know why this is? I know how to fix this problem using ViewState however that is not my prefered way of going about this.

Anyways i know this is off the subject i posted under.
Your advice so far will help me quite a bit in the future.

Thanks again!!


Ok so I’ve given this a serious go now.
Actually my logic seem to work just fine. The code does increment the value set at the top of the page when i click my forward button and the "StepForward()" method is called. Only one problem now...
When i click the forward button for the second time... it doesn't increment that value again to 3. It just stays there on 2. (I pass to the class constructor the initial value to 1)
Since VS doesn't want to break into debugger so i can step through the code i have to assume that the variable is stuck in some way.

I use the word 'stuck' because the value isn't incremented beyond 2, however once i call the "StepPrevious()" method the value is decremented back to 1.
So it isn't a case of either loosing the value or it being set back to the initial value of 1 with every server round trip. (If it was reset during server round trip the value would have been 0)

Kris would you know why this is? I know how to fix this problem using ViewState however that is not my preferred way of going about this.

Anyways I know this is off the subject i posted under.
Your advice so far will help me quite a bit in the future.

Thanks again!!

Object Reference

Hello,

I have a rather large web app that I'm trying to debug and I get this error on multiple pages:

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

The error is pointing at my insert statement but there is nothing wrong with the statement. I've also checked to make sure that each field in the web app has a place in the insert statement, verified the names in the DB with the names in the insert statement and made sure that the values in the insert statement are correct with the names in the SQL placeholders (@dotnet.itags.org.variable).

I don't understand this error. Any ideas?

DaleThe error is actually with your .NET code. On your command, I can place a bet that it is nulled/nothing. You must create a new instance of the command. For example:


SqlCommand command = null; // you must have something like this

...

// but this is correct
SqlCommand command =new SqlCommand();


Okay. So if I have it setup as in the following:


Dim DBConnect As New SqlConnection
Dim InsertStatement As New SqlCommand

DBConnect.ConnectionString = ("server=SERVER;database=DATABASE;uid=SA;password=PASSWORD")

InsertStatement.CommandText = "Insert TABLE (Column1, Column2) & _
"Values (@.Column1, @.Column2)"

InsertStatement.Parameters.Add("@.Column1", SqlDatatype, Char, 30).Values=txtColumn1.Text

InsertStatement.Parameters.Add("@.Column2", SqlDatatype, Char, 30).Values=txtColumn2.Text

...

Where/how do I add the "SqlCommand Command = New SqlCommand()"?

Thanks again,
Dale
That code was in C#... you are coding in VB.NET. You have the equivelence over here -- so which line is giving you the problem?
Well, it is specifying the acutal insert statement as the pint of failure.

(** In my last post I fogot to type the " at the end of the statement, I've corrected this below.)


InsertStatement.CommandText = "Insert TABLE (Column1, Column2)" & _

So you typed this online then? If you have then you have just found a "silly" typing error. In your original code, you might have this:

Dim InsertStatement As SqlCommand ' notice the "new" missing

However you must create a new instance of the InsertCommand variable. You have done this in the above post but you could have overread your original code. It should be creating a new instance like here:

Dim InsertStatement As New SqlCommand

Not a problem Dale.
Yes, if fact I just added that to my code to see if that was the issue. check back to see if it worked. Thanks a TON!

Dale

Object reference

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 40: dtagrdReviewDisplay.DataBind();Line 41: //dropdownlistLine 42: drpdwnRevRating.Items[0].Selected=true;Line 43: drpdwnProRating.Items[0].Selected=true;Line 44:

Is there anything loaded into the dropDown?

You may want to make your code like this to prevent the error:

if(drpdwnRevRating.Items.Count > 0)

drpdwnRevRating.Items[0].Selected = true;

if(drpdwnProRating.Items.Count > 0)

drpdwnProRating.Items[0].Selected = true;


the rating dropdown has ratings 1 to 10,Autopostback property is set to true.

so when the user selects the rating,the new rating is shown in the label and when the forms reloads i want to make Select one as the item to be diplayed.


How about trying the code I sent just to get the page to load. Then you can see if there is actually anything in your dropdownlist. I tried to recreate your error and the only way I can is if I don't put anything into the dropdownlist.

Let me know what happens when you try those 'if' statements.


i have datagrid ,in datagrid i have one drop down,this dropdown has 1 to 10 as listitems

i want to catch the rating what the user has selected so

.aspx

<asp:DropDownList id="drpdwnRevRating" AutoPostBack="True" Runat="server">
<asp:ListItem Selected="True" Value="Select One">Select One</asp:ListItem>
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
<asp:ListItem Value="4">4</asp:ListItem>
<asp:ListItem Value="5">5</asp:ListItem>
<asp:ListItem Value="6">6</asp:ListItem>
<asp:ListItem Value="7">7</asp:ListItem>
<asp:ListItem Value="8">8</asp:ListItem>
<asp:ListItem Value="9">9</asp:ListItem>
<asp:ListItem Value="10">10</asp:ListItem>
</asp:DropDownList>
<br>
Rate the Product:
<asp:DropDownList>
<asp:ListItem Value="1">1</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>

.cs

privatevoid dtagrdReviewDisplay_SelectedIndexChanged(object sender, System.EventArgs e)

{

string strRevRating;

strRevRating=Request["drpdwnRevRating"];

Response.Write(strRevRating);

}

Output notthing is coming in strRevRating and i used break point here,the comilation is not coming into this eventhandler itself.


is their is any problem in this event handler of dropdownlist control what i wrote

protected System.Web.UI.WebControls.DropDownList drpdwnRevRating;

this.drpdwnRevRating.SelectedIndexChanged += new System.EventHandler(this.drpdwnRevRating_SelectedIndexChanged);


private void drpdwnRevRating_SelectedIndexChanged(object sender, System.EventArgs e)
{
string strRevRating;
strRevRating=Request["drpdwnRevRating"];
Response.Write(strRevRating);

}

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 65: { Line 66: this.ImageButton1.Click += new System.Web.UI.ImageClickEventHandler(this.ImageButton1_Click);Line 67: this.drpdwnRevRating.SelectedIndexChanged += new System.EventHandler(this.drpdwnRevRating_SelectedIndexChanged);Line 68: this.Load += new System.EventHandler(this.Page_Load);Line 69:


I think the issues you are having is because the DropDownList does not belong to the page, it belongs to the datagrid. The null exception is because there is no "this.drpdwnRevRating".

To work with the dropdownlists, you must find the control on the line of the datagrid and cast it to a DropDownList. I assume you are using ASP.Net 1.1 which I don't have installed on this computer or I would type up a quick sample, but you can refer to this article.http://www.codeproject.com/aspnet/DataGridDropDownList.asp

Pay attention to how they are doing:

DropDownList dl = (DropDownList)(dgi.Cells[2].Controls[1]);

You can also do:

DropDownList dl = (DropDownList)(dgi.Rows[e.SelectedIndex].FindControls("drpdwnProRating");

//I think that is the right syntax but I don't have the luxury of intellisense right now.

Then you can work with 'dl' instead of 'drpdwnProRating'

I hope that helps to move your forward a bit.

Object Reference Blah Blah & Code Behind

I am getting this error:
Object reference not set to an instance of an object

On this line of my code:

dgNewsItems.DataSource = myDataSet.Tables("News")

I can't see what the problem would be...

Here's my full code:
News.aspx

<%@dotnet.itags.org. Page Language="VB" Debug="true" Inherits="clsNews" src="http://pics.10026.com/?src=..\code\news.vb" %
<html>
<head>
<title>Admin - News</title>
</head>
<body>
<asp:datagrid ID="dgNewsItems" runat="server" />
</body>
</html>

news.vb

Imports System
Imports System.Configuration
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.OleDb

Public Class clsNews : Inherits Page
'Declare public variables for .aspx file to inherit
Dim dgNewsItems as DataGrid

Sub Page_Load(sender as Object, e as EventArgs)
If Not Page.IsPostBack Then
FillDataGrid()
End If
End Sub 'Page_Load

Private Sub FillDataGrid()
Dim strConn as String = ConfigurationSettings.AppSettings("ConnectionString")
Dim strCmd as String = "SELECT * FROM News"
Dim myDataSet as New DataSet()

Dim myConn as New OleDbConnection(strConn)
Dim myCmd as New OleDbDataAdapter(strCmd, myConn)

myConn.Open()
myCmd.Fill(myDataSet, "News")

dgNewsItems.DataSource = myDataSet.Tables("News")
dgNewsItems.DataBind()
myConn.Close()
End Sub 'FillDataGrid
End Class

Cheers
Charles VTry giving
myCmd.Fill(myDataSet, "News1")
dgNewsItems.DataSource = myDataSet.Tables("News1")

or
dgNewsItems.DataSource = myDataSet.Tables(0)

or
dgNewsItems.DataSource = myDataSet

does that make difference??

Have you changed the statement as
<%@. Page Language="VB" Debug="true" Inherits="clsNews" src="http://pics.10026.com/?src=..\code\news.vb" %
hmm

None of those made any difference...

What do you mean by 'Have you changed the statement as'?

Charles V
I found the error

This line:
Dim myCmd as New OleDbDataAdapter(strCmd, myConn)

Is supposed to be:
Dim myCmd as OleDbDataAdapter = New OleDbDataAdapter(strCmd, myConn)

So simple........

Object Reference error

Hi

I have the following code in an asp.net file:

<div id="header">
Home     |   Computers     |   Laptops     |   PDAs     |   Accessories     |   Networks     |   Monitors     |   Keyboards/Mice    
</div>
<asp:ListBox ID="lbsmenu" runat="server" SelectionMode=Multiple></asp:ListBox>
<form id="form1" runat="server">
<p> Enter Name </p>

<asp:TextBox ID="tbBike" runat="server" > </asp:TextBox>
<br />
<asp:Button ID="btBike" runat="server" Text="Click Here" OnClick="btBike_Click" />
<br />
</form>
</div>

I also have the following code in a c# file:

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlConn = connection.connect();
sqlConn.Open();

SqlCommand menubar = new SqlCommand("Select * from Menu_table", sqlConn);
SqlDataAdapter dataAdapter5 = new SqlDataAdapter();
dataAdapter5.SelectCommand = menubar;
DataSet dataSet5 = new DataSet();
dataAdapter5.Fill(dataSet5);
DataTable selcartest4 = dataSet5.Tables["table"];

for (int i = 0; i < selcartest4.Rows.Count; i++)
{

Session["selCommunities"] = selcartest4.Rows[i]["Menu_id"].ToString().Trim();
string selCommunities = Session["selCommunities"].ToString().Trim();
lbsmenu.Items.FindByValue(selCommunities).Selected = true;

}

}

However I keep getting an object reference error for the lbsmenu bit of code shown above.

I am using visual web developer

Any solutions would be great

cheers

Jamie

Have you initialized lbsmenu.Items collection with values anywhere? Otherwise the items collection is nothing.


You should populate lbsMenu's ListItem collection with list values.


Make sure you set the

DataValueField
or else if you use
new ListItem(<text>,<value>);
  check whether <value> is set.
 Since you use FindByValue(string searchkey), which is case sensitive, returns null item if list items value doesn't match with the searchkey.
 

Sorry I am not sure what you mean, could you give me an example please

thankyou


Sorry for late reply,Big Smile

Did you set data source for the ListBox or add list item manually?

If former case ,

you should set

DataValueField
of the list box before calling
FindByValue

method.

If latter case,

which means you populate list box by calling

ListBox1.Items.Add(new ListItem("Text here","Value here"));

second parameter we can omit. But it should set, before calling

FindByValue

Other thing is, parameter value for the FindByValue is case sensitive. if that doesn't match it will returns null listItem. then you will get object reference error.

Hope you got the answer.


Hi James,

I agree with the member above. We should make sure that the item we get using FindByValue method is not null.

Besides, the ListBox control should be placed within a form tag with runat=server.


I hope this helps.

Object reference error

 Hi this is my code ;
protectedvoid CreateUserWizard1_CreatingUser(object sender,LoginCancelEventArgs e)

{

MSCaptcha.CaptchaControl loginCAPTCHA = (MSCaptcha.CaptchaControl)LoginCredentials.FindControl("ccJoin");

TextBox txtCap = (TextBox)LoginCredentials.FindControl("txtJoin");Label captchalabel = (Label)LoginCredentials.FindControl("Captcha");

loginCAPTCHA.ValidateCaptcha(txtCap.Text);

if (!loginCAPTCHA.UserValidated)

{

captchalabel.Text ="Please Try Again ";

return;

}

}

I am getting Object reference not set to an instance of an object error. at the following line.

loginCAPTCHA.ValidateCaptcha(txtCap.Text);
Could someone tell me what the problem is.

Thank You

Kind of hard to say without knowing which Captcha control you're using. I googled on MSCaptcha.CaptchaControl but came up blank. If i google for MSCaptcha, I only come up with this:

http://www.mondor.org/soft/captcha.htm

If that's what you're using, did you enter the code to your web.config file, and then put the following into your registration page?

(this goes at the top)

<%@.RegisterAssembly="MSCaptcha"Namespace="MSCaptcha"TagPrefix="cc1" %>

(this goes where you want to show the captcha)

<cc1:CaptchaControlID="ccJoin"runat="server"CaptchaBackgroundNoise="none"CaptchaLength="5"CaptchaHeight="60"CaptchaWidth="200"CaptchaLineNoise="None"CaptchaMinTimeout="5"CaptchaMaxTimeout="240"/>

If you did all that, you shouldn't have to do the three lines of code you entered first. txtCap is just a Textbox where the user has to type the value shown by the Captcha.

I've recently implemented a Captcha myself, and I used the one from

http://www.codeproject.com/aspnet/CaptchaControl.asp. If you want a C# version, check the comments. There's a translated version in there. Also be sure to check the reply to the comment.

Also, just out of curiosity, did you mark your post as an answer because you managed to figure it out, or do you still require help?

HTH.

Peter


Hi Thanks for your reply.

I fixed that problem my controls were inside a contenttemplatecontainer. So I should have used

MSCaptcha.CaptchaControl loginCAPTCHA = (MSCaptcha.CaptchaControl)LoginCredentials.ContentTemplateContainer .FindControl("ccJoin");

instead of

MSCaptcha.CaptchaControl loginCAPTCHA = (MSCaptcha.CaptchaControl)LoginCredentials.FindControl("ccJoin");

But now I am up against another task displaying the Duplicateusernameerrormessage label.

If I enter a duplicate username or email the create user wizard doesn't create the user that is fine . But I want it to display the error message in a label. How can I do this?

Thanks


Dont know how is you captcha located but use this--If you show your UI code I can tell you specifics but following should solve it..

firstly you should modify the code to check for null...

secondly this is how you can find it.

MSCaptcha.CaptchaControl CreateUserWizard1CAPTCHA = (MSCaptcha.CaptchaControl)CreateUserWizardStep1.ContentTemplateContainer.FindControl("CAPTCHA");

if the stuff is increate user step 1.


bendJoe:

Hi Thanks for your reply.

I fixed that problem my controls were inside a contenttemplatecontainer. So I should have used

MSCaptcha.CaptchaControl loginCAPTCHA = (MSCaptcha.CaptchaControl)LoginCredentials.ContentTemplateContainer .FindControl("ccJoin");

instead of

MSCaptcha.CaptchaControl loginCAPTCHA = (MSCaptcha.CaptchaControl)LoginCredentials.FindControl("ccJoin");

But now I am up against another task displaying the Duplicateusernameerrormessage label.

If I enter a duplicate username or email the create user wizard doesn't create the user that is fine . But I want it to display the error message in a label. How can I do this?

Thanks

Set the error message of validators inside create user wizard.


I'm not sure if it is set automatically, but you can always use the

CreateUserWizard1.DuplicateEmailErrorMessage

property. You most likely will be able to set it in the aspx file, and from the codebehind, you can catch any errors, and assign them to a hidden label that you unhide when the error pops up.

HTH

Peter


It is set automatically, by default its just a *, you can set it both in cb or in aspx file


I just started testing with a sample createuserwizard and found these. There is a literal which displays a message saying please enter a different user name. I need a similar mechanism for e-mail also. How can I do this?

Object reference error

I have a datagrid and each column contains a different controls. When Iam trying to access the value of the ListBox controls inside thedatagrid it keeps on throwing "Object reference not set to an instanceof an object". The line is bold where it throws the error.
Here is my code:
private void Button1_Click(object sender, System.EventArgs e)
{
StringBuilder str = new StringBuilder();

foreach(DataGridItem dgi in myDataGrid.Items)
{
TextBox myTextBox = (TextBox)(dgi.Cells[0].Controls[1]);
ListBox myListBox = (ListBox)(dgi.Cells[1].Controls[1]);
DropDownList myList = (DropDownList)(dgi.Cells[2].Controls[1]);
CheckBox myCheckBox = (CheckBox)(dgi.Cells[3].Controls[1]);
str.Append(myTextBox.Text);
if(myListBox.SelectedItem.Value != null)
{
str.Append(myListBox.SelectedItem.Text);
}


str.Append(myList.SelectedItem.Text);
str.Append(myCheckBox.Checked);


}

Probably my eyes but there's no line in bold.

If you debug and check the type of the controls that you're using, are they of the correct type? I know I had some trouble in the past that sometimes I had to take Controls[0] and sometimes Controls[1] to obtain the correct control.

Grz, Kris.


Yeah I tried using Controls[0] but it did not worked and gave me that "Specific cast is not valid" error. The bold line below causes "Object reference not set to an instance of an object" This error is only thrown when I dont select any item in the ListBox.

foreach(DataGridItem dgiin myDataGrid.Items)

{

TextBox myTextBox = (TextBox) (dgi.Cells[0].Controls[1]);

ListBox myListBox = (ListBox) (dgi.Cells[1].Controls[1]);

DropDownList myList = (DropDownList) (dgi.Cells[2].Controls[1]);

CheckBox myCheckBox = (CheckBox) (dgi.Cells[3].Controls[1]);

str.Append(myTextBox.Text);

if(myListBox.SelectedItem.Value !=null)

{

str.Append(myListBox.SelectedItem.Text);

}

str.Append(myList.SelectedItem.Text);

str.Append(myCheckBox.Checked);

}


Okay I got it. I had to get the value from the ListBox into a string variable and than compare the string to null and empty.
The following code works:
foreach(DataGridItem dgi in myDataGrid.Items)
{
TextBox myTextBox = (TextBox)(dgi.Cells[0].Controls[1]);
ListBox myListBox = (ListBox)(dgi.Cells[1].Controls[1]);
DropDownList myList = (DropDownList)(dgi.Cells[2].Controls[1]);
CheckBox myCheckBox = (CheckBox)(dgi.Cells[3].Controls[1]);
str.Append(myTextBox.Text);
string a = myListBox.SelectedValue;
//string b = myListBox.SelectedItem.Value;
//string c = myListBox.SelectedItem.Text;
if(a != null && a != "")
{
str.Append(myListBox.SelectedItem.Text);
}


str.Append(myList.SelectedItem.Text);
str.Append(myCheckBox.Checked);


}

Object Reference error

I have a live ASP.NET site that in general runs very well. However, I am trapping errors and having the error message emailed to me. Everything will run fine but then sporadically, I will receive the following message:

Server Error in '/' Application.

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.] MeetMarket3.SideBar.Page_Load(Object sender, EventArgs e) System.Web.UI.Control.OnLoad(EventArgs e) +67 System.Web.UI.Control.LoadRecursive() +35 System.Web.UI.Page.ProcessRequestMain() +750

Request URL: /sidebar.aspx

User:656
ScreenName:2lookingtoplay
Last SQL:exec dbo.spStateList

I am using Cookies to store the UserID and it appears as though this cookie information will get lost. Is there anything that could happen to cause Cookies to get reset?

Greg

There are a number of reasons ranging from why cookies get lost, including the user clearing them out or the plain old fact that they just expire. You must always code defensively when reading from cookies, query strings, form variables and so forth, which means that you must always check to see if the item is null/Nothing before you read from it.

Thanks.

I know that the user is not clearing them as this has happened to me while on the site.

I was under the empression that if you did not set an expiration that they would be valid at least throughout the current browser session. Is that not true?

Greg

object reference error and stored procedure

This has been a fun day, let me tell you. Anyway, I have a helper class that handles my database calls (ok, 3 of them, but DatabaseAccess is the main one) and its used as such from within the global.ascx file... for reference Utilities.UserName just strips out the <DOMAIN> part of the username (I'm using windows authen) and GetMyDepartments executes a scalar command and returns a string.

1void Session_Start(object sender, EventArgs e)
2 {
3string userName = Utilities.UserName(Request.LogonUserIdentity.Name);
4string deptID = DatabaseAccess.GetMyDepartment(userName);
56 Session.Add("UserName", userName);
7 Session.Add("DeptID", deptID);
89if (deptID ==string.Empty)
10 {
11 Response.Redirect("setup.aspx");
12 }
13 }

The problem happens at line 4. If a user has a department ID, its happy and goes about its business with no problem ...but as soon as it doesn't (from, say, a new user that hasn't accessed the site) it throws a nasty Object reference not set to an instance of an object. And I have -no- clue why. I've tried dropping it into page_loads and even profiles but no help. So what am I overlooking?

If you traced GetMyDepartment() you'd see that when it fails, it fails to return a proper string. The object (a DataSet maybe?) doesn't get created. Make sure that if it fails, it exits gracefully returning String.Empty which is what you are checking for in the returned value.

The object -should- end up as a string (since execute scalar returns column[0] cell[0]) -- and this works for 5 or 6 other scalars commands as well which is why its confusing me to no end. Maybe this'll help some more ...the code behind the dbaccess looks something like this

1public static string GetMyDepartment(string userName)2 {3 DbCommand comm = DataAccess.CreateCommand();4 comm.CommandText ="GetMyDepartment";5 comm.Parameters.Add(DatabaseParameter.Str(comm,"@.UserName", userName, 25));6return DataAccess.ExecuteScalar(comm);7 }
1public static string ExecuteScalar(DbCommand command)2 {3string value =string.Empty;4try5 {6 command.Connection.Open();7value = command.ExecuteScalar().ToString();8 }9catch (Exception ex)10 {11 Utilities.LogError(ex);12throw ex;13 }14finally15 {16 command.Connection.Close();17 }18return value;19 }

The problem comes from the executescalar.

on line 7 in ExecuteScalar, command.ExecuteScalar() will return null when the resultset is empty.Applying ToString() will raise an error that you log ...but throw again. This error will be propagated to your initial calling function in global.asax.


Got it. I switched out the datatype from string to object (since thats what ExecuteScalar() returns anyway) and check for a null value before returning that value as such...

1public static string ExecuteScalar(DbCommand command)2 {3object value =new object();4try5 {6 command.Connection.Open();7value = command.ExecuteScalar();8 }9catch (Exception ex)10 {11 Utilities.LogError(ex);12throw ex;13 }14finally15 {16 command.Connection.Close();17 }1819if (value ==null)20 {21value =string.Empty;22 }23return value.ToString();24 }
works like a charm. Thanks.

Object reference error : Cookies

I get the following error message:

Object reference not set to an instance of an object

With a reference to the following line of code:

UserID = ctype(request.cookies("Details")("UserID"),integer)

In the login page I created the cookie with the following line of code:

 response.cookies("Details")("Login")=Login.Text

I am new to using cookies so I was hoping someone might help me out.

I think I may have cheated when creating the cookie so it is not set up properly??

Any help would be great
ThanksHello, what is UderID ?
is is a textbox ? a label ? if yes

u should use
UderId.Text = ......

Object reference error - Microsoft code

I am getting an error "Object reference not set to an instance of an
object." using code taken directly from MSDN for
GridViewUpdatedEventArgs.OldValues property. I am trying to view the old and
new values from before and after a row is updated. Below is the code I am
using in 2 subs. The error occurs at both the lines that call the
DisplayValues sub and on the setting of txtMsg.Text value in the For...Next
loop of the DisplayValues sub. Can someone help me with getting this to
work? Thanks.
p.s. Below the code for the 2 subs is the Stack Trace.
Protected Sub SubfilesGridView_RowUpdated(ByVal sender As Object, ByVal
e As GridViewUpdatedEventArgs)
' Use the Exception property to determine whether an exception
' occurred during the update operation.
If e.Exception Is Nothing Then
If e.AffectedRows = 1 Then
' Use the Keys property to get the value of the key field.
Dim keyFieldValue As String = e.Keys("ID").ToString()
' Display a confirmation message.
txtMsg.Text = "Record " & keyFieldValue & _
" updated successfully. "
' Display the new and original values.
DisplayValues(CType(e.NewValues, OrderedDictionary),
CType(e.OldValues, OrderedDictionary))
Else
' Display an error message.
txtMsg.Text = "An error occurred during the update
operation."
' When an error occurs, keep the GridView control in edit
mode.
e.KeepInEditMode = True
End If
Else
' Insert the code to handle the exception.
txtMsg.Text = e.Exception.Message
' Use the ExceptionHandled property to indicate that the
' exception is already handled.
e.ExceptionHandled = True
e.KeepInEditMode = True
End If
End Sub
Protected Sub DisplayValues(ByVal newValues As OrderedDictionary, ByVal
oldValues As OrderedDictionary)
txtMsg.Text &= "<br/></br>"
' Iterate through the new and old values. Display the values on the
page.
Dim i As Integer
For i = 0 To oldValues.Count - 1
txtMsg.Text &= "Old Value=" & oldValues(i).ToString() & _
", New Value=" & newValues(i).ToString() & "<br/>"
Next
txtMsg.Text &= "</br>"
End Sub
Stack Trace:
at ASP.frmfileedit_aspx.DisplayValues(OrderedDictionary newValues,
OrderedDictionary oldValues) in
http://server//Fileroom/frmFileEdit.aspx:line 1615
at ASP.frmfileedit_aspx.SubfilesGridView_RowUpdated(Object sender,
GridViewUpdatedEventArgs e) in http://server//Fileroom/frmFileEdit.aspx:line
1588
at
System.Web.UI.WebControls.GridView.OnRowUpdated(GridViewUpdatedEventArgs e)
at System.Web.UI.WebControls.GridView.HandleUpdateCallback(Int32
affectedRows, Exception ex)
at System.Web.UI.DataSourceView.Update(IDictionary keys, IDictionary
values, IDictionary oldValues, DataSourceViewOperationCallback callback)
at System.Web.UI.WebControls.GridView.HandleUpdate(GridViewRow row, Int32
rowIndex, Boolean causesValidation)
at System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean
causesValidation, String validationGroup)
at System.Web.UI.WebControls.GridView.OnBubbleEvent(Object source,
EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source,
EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e)
at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String
eventArgument)
at
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.Rai
sePostBackEvent(String
eventArgument)
at System.Web.UI.Page. RaisePostBackEvent(IPostBackEventHandler
sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)In Display function instead of oldValues(i).ToString() try to
Convert.ToString(oldValues(i))
ToString() does not checks for NULL and thorws an exception while
Conver.ToString() handles
NULL.
Thanks
Sachin Saki
"David C" wrote:

> I am getting an error "Object reference not set to an instance of an
> object." using code taken directly from MSDN for
> GridViewUpdatedEventArgs.OldValues property. I am trying to view the old a
nd
> new values from before and after a row is updated. Below is the code I am
> using in 2 subs. The error occurs at both the lines that call the
> DisplayValues sub and on the setting of txtMsg.Text value in the For...Nex
t
> loop of the DisplayValues sub. Can someone help me with getting this to
> work? Thanks.
> p.s. Below the code for the 2 subs is the Stack Trace.
> Protected Sub SubfilesGridView_RowUpdated(ByVal sender As Object, ByVa
l
> e As GridViewUpdatedEventArgs)
> ' Use the Exception property to determine whether an exception
> ' occurred during the update operation.
> If e.Exception Is Nothing Then
> If e.AffectedRows = 1 Then
> ' Use the Keys property to get the value of the key field.
> Dim keyFieldValue As String = e.Keys("ID").ToString()
> ' Display a confirmation message.
> txtMsg.Text = "Record " & keyFieldValue & _
> " updated successfully. "
> ' Display the new and original values.
> DisplayValues(CType(e.NewValues, OrderedDictionary),
> CType(e.OldValues, OrderedDictionary))
> Else
> ' Display an error message.
> txtMsg.Text = "An error occurred during the update
> operation."
> ' When an error occurs, keep the GridView control in edit
> mode.
> e.KeepInEditMode = True
> End If
> Else
> ' Insert the code to handle the exception.
> txtMsg.Text = e.Exception.Message
> ' Use the ExceptionHandled property to indicate that the
> ' exception is already handled.
> e.ExceptionHandled = True
> e.KeepInEditMode = True
> End If
> End Sub
> Protected Sub DisplayValues(ByVal newValues As OrderedDictionary, ByVa
l
> oldValues As OrderedDictionary)
> txtMsg.Text &= "<br/></br>"
> ' Iterate through the new and old values. Display the values on th
e
> page.
> Dim i As Integer
> For i = 0 To oldValues.Count - 1
> txtMsg.Text &= "Old Value=" & oldValues(i).ToString() & _
> ", New Value=" & newValues(i).ToString() & "<br/>"
> Next
> txtMsg.Text &= "</br>"
> End Sub
>
> Stack Trace:
> at ASP.frmfileedit_aspx.DisplayValues(OrderedDictionary newValues,
> OrderedDictionary oldValues) in
> http://server//Fileroom/frmFileEdit.aspx:line 1615
> at ASP.frmfileedit_aspx.SubfilesGridView_RowUpdated(Object sender,
> GridViewUpdatedEventArgs e) in [url]http://server//Fileroom/frmFileEdit.aspx:line[/ur
l]
> 1588
> at
> System.Web.UI.WebControls.GridView.OnRowUpdated(GridViewUpdatedEventArgs e
)
> at System.Web.UI.WebControls.GridView.HandleUpdateCallback(Int32
> affectedRows, Exception ex)
> at System.Web.UI.DataSourceView.Update(IDictionary keys, IDictionary
> values, IDictionary oldValues, DataSourceViewOperationCallback callback)
> at System.Web.UI.WebControls.GridView.HandleUpdate(GridViewRow row, Int
32
> rowIndex, Boolean causesValidation)
> at System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean
> causesValidation, String validationGroup)
> at System.Web.UI.WebControls.GridView.OnBubbleEvent(Object source,
> EventArgs e)
> at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args
)
> at System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source,
> EventArgs e)
> at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args
)
> at System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e)
> at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String
> eventArgument)
> at
> System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.R
aisePostBackEvent(String
> eventArgument)
> at System.Web.UI.Page. RaisePostBackEvent(IPostBackEventHandler
> sourceControl, String eventArgument)
> at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
> at System.Web.UI.Page.ProcessRequestMain(Boolean
> includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
>
>
That did it! Thank you Sachin.
David
"Sachin Saki" <SachinSaki@.discussions.microsoft.com> wrote in message
news:90AC2594-FC34-4A16-B6D2-56AEC238DF97@.microsoft.com...
> In Display function instead of oldValues(i).ToString() try to
> Convert.ToString(oldValues(i))
> ToString() does not checks for NULL and thorws an exception while
> Conver.ToString() handles
> NULL.
> Thanks
> Sachin Saki
> "David C" wrote:
>

Object reference error

Private Sub cmdLeftRight_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles cmdLeftRight.Click, cmdCenterRight.Click, cmdCenterLeft.Click, cmdRightLeft.Click

Dim sourcePane As String = CType(sender, ImageButton).Attributes("sourcepane")
Dim targetPane As String = CType(sender, ImageButton).Attributes("targetpane")
Dim sourceBox As ListBox = CType(Page.FindControl(sourcePane), ListBox)
Dim targetBox As ListBox = CType(Page.FindControl(targetPane), ListBox)

end sub

why i can not find my control with the "Page.FindControl" method?
the string name is correcte, the control exist on my page. I still have that error "object reference not set to an instance of..object"

what do i do wrong here !!

thanxYou haven't provided enough information for us to answer your question. Whether Page.FindControl will actually find a control depends on where the control is on your page.

To see what I mean - and hopefully to allow you to solve your own problem - please read:
In Search Of Controls

As an aside, you should always test whether an object has a value before you start working with it.

For example, you should do something like:

' Find the target pane
Dim FoundTargetPane As Control
FoundTargetPane = Page.FindControl( targetPane )

' If found, cast the target pane to a ListBox control
Dim targetBox As Listbox
If Not FoundTargetPane Is Nothing Then
targetBox = CType( FoundTargetPane, ListBox )
End If

' Work with the targetBox
If Not targetBox Is Nothing Then
' we can work with targetBox, knowing that's we've found it
End If

Monday, March 26, 2012

Object reference error in UserControl's Load event

I have a UserControl that I declare programmatically as follows:

Dim userctrl as New rightside_portal()

The codebehind file for this UserControl looks like the following:

Partial Public Class rightside_portal : Inherits System.Web.UI.UserControl

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load

Const renewurl As String = "http://www.renewingsite.com/"

Me.lblExpiresOn.Text = String.Format("IMPORTANT<br/>Your account is set to
expire {0}. To renew your membership, please ", "EXPIRATIONDATE")

Me.lnkRenew.NavigateUrl = renewurl

Me.lnkSaveToday.NavigateUrl = renewurl

End Sub

End Class

However, I receive the following error when I run the application:

Server Error in '/' Application.
------------------------

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.]
AFBE.rightside_portal.Page_Load(Object sender, EventArgs e) +59
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061

------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET
Version:2.0.50727.210

I am pretty sure the problem has something to do with the fact that I am
declaring the UserControl in my codebehind rather than my *.aspx file, but I
am not quite sure what I need to do differently. If anyone can help me, I
would appreciate it. Thanks.
--
Nathan Sokalski
njsokalski@dotnet.itags.org.hotmail.com
http://www.nathansokalski.com/you can't create a "new UserContorl();"

you need to use Page.LoadControl("~/controls/test.ascx");

Using "new" creates a new instance of the class, but doesn't instanticate
the aspx class. therefore lblExpires is never created and you end up with a
null reference.

Karl

--
http://www.openmymind.net/
http://www.codebetter.com/
"Nathan Sokalski" <njsokalski@.hotmail.comwrote in message
news:Oiui$QWMHHA.992@.TK2MSFTNGP06.phx.gbl...

Quote:

Originally Posted by

>I have a UserControl that I declare programmatically as follows:
>
Dim userctrl as New rightside_portal()
>
The codebehind file for this UserControl looks like the following:
>
Partial Public Class rightside_portal : Inherits System.Web.UI.UserControl
>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
>
Const renewurl As String = "http://www.renewingsite.com/"
>
Me.lblExpiresOn.Text = String.Format("IMPORTANT<br/>Your account is set to
expire {0}. To renew your membership, please ", "EXPIRATIONDATE")
>
Me.lnkRenew.NavigateUrl = renewurl
>
Me.lnkSaveToday.NavigateUrl = renewurl
>
End Sub
>
End Class
>
>
However, I receive the following error when I run the application:
>
Server Error in '/' Application.
------------------------
>
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.]
AFBE.rightside_portal.Page_Load(Object sender, EventArgs e) +59
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061
>
>
>
------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.42;
ASP.NET Version:2.0.50727.210
>
I am pretty sure the problem has something to do with the fact that I am
declaring the UserControl in my codebehind rather than my *.aspx file, but
I am not quite sure what I need to do differently. If anyone can help me,
I would appreciate it. Thanks.
--
Nathan Sokalski
njsokalski@.hotmail.com
http://www.nathansokalski.com/
>

Object Reference Error Message

When executing the following code, I get this error message:
Object reference not set to an instance of an object
It bombs out on me rigth at the cmdWO.CommandText statement.
If you have any ideas, please share them!
Dim strWO As String
Dim rdrWO As System.Data.SqlClient.SqlDataReader
Me.cnnContract.Open()
cmdWO.Connection = cnnContract
cmdWO.CommandText = "Select * from ContractOutWO where ID="
& txtFind.Text
rdrWO = cmdWO.ExecuteReader
With rdrWO
While .Read
strWO = strWO & rdrWO.GetString(1) & ","
'.NextResult()
End While
End With
rdrWO.Close()txtFind is not defined
Eliyahu
<tjonsek@.phenom-biz.com> wrote in message
news:1135092294.098801.62040@.f14g2000cwb.googlegroups.com...
> When executing the following code, I get this error message:
> Object reference not set to an instance of an object
> It bombs out on me rigth at the cmdWO.CommandText statement.
> If you have any ideas, please share them!
> Dim strWO As String
> Dim rdrWO As System.Data.SqlClient.SqlDataReader
> Me.cnnContract.Open()
> cmdWO.Connection = cnnContract
> cmdWO.CommandText = "Select * from ContractOutWO where ID="
> & txtFind.Text
>
> rdrWO = cmdWO.ExecuteReader
> With rdrWO
> While .Read
>
> strWO = strWO & rdrWO.GetString(1) & ","
> '.NextResult()
> End While
> End With
> rdrWO.Close()
>

Object reference error in UserControl's Load event

I have a UserControl that I declare programmatically as follows:
Dim userctrl as New rightside_portal()
The codebehind file for this UserControl looks like the following:
Partial Public Class rightside_portal : Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
Const renewurl As String = "http://www.renewingsite.com/"
Me.lblExpiresOn.Text = String.Format("IMPORTANT<br/>Your account is set to
expire {0}. To renew your membership, please ", "EXPIRATIONDATE")
Me.lnkRenew.NavigateUrl = renewurl
Me.lnkSaveToday.NavigateUrl = renewurl
End Sub
End Class
However, I receive the following error when I run the application:
Server Error in '/' Application.
----
--
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.]
AFBE.rightside_portal.Page_Load(Object sender, EventArgs e) +59
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061
----
--
Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET
Version:2.0.50727.210
I am pretty sure the problem has something to do with the fact that I am
declaring the UserControl in my codebehind rather than my *.aspx file, but I
am not quite sure what I need to do differently. If anyone can help me, I
would appreciate it. Thanks.
--
Nathan Sokalski
njsokalski@dotnet.itags.org.hotmail.com
http://www.nathansokalski.com/you can't create a "new UserContorl();"
you need to use Page.LoadControl("~/controls/test.ascx");
Using "new" creates a new instance of the class, but doesn't instanticate
the aspx class. therefore lblExpires is never created and you end up with a
null reference.
Karl
http://www.openmymind.net/
http://www.codebetter.com/
"Nathan Sokalski" <njsokalski@.hotmail.com> wrote in message
news:Oiui$QWMHHA.992@.TK2MSFTNGP06.phx.gbl...
>I have a UserControl that I declare programmatically as follows:
> Dim userctrl as New rightside_portal()
> The codebehind file for this UserControl looks like the following:
> Partial Public Class rightside_portal : Inherits System.Web.UI.UserControl
> Protected Sub Page_Load(ByVal sender As Object, ByVal e As
> System.EventArgs) Handles Me.Load
> Const renewurl As String = "http://www.renewingsite.com/"
> Me.lblExpiresOn.Text = String.Format("IMPORTANT<br/>Your account is set to
> expire {0}. To renew your membership, please ", "EXPIRATIONDATE")
> Me.lnkRenew.NavigateUrl = renewurl
> Me.lnkSaveToday.NavigateUrl = renewurl
> End Sub
> End Class
>
> However, I receive the following error when I run the application:
> Server Error in '/' Application.
> ----
--
> 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.]
> AFBE.rightside_portal.Page_Load(Object sender, EventArgs e) +59
> System.Web.UI.Control.OnLoad(EventArgs e) +99
> System.Web.UI.Control.LoadRecursive() +47
> System.Web.UI.Control.LoadRecursive() +131
> System.Web.UI.Control.LoadRecursive() +131
> System.Web.UI.Control.LoadRecursive() +131
> System.Web.UI.Control.LoadRecursive() +131
> System.Web.UI.Page.ProcessRequestMain(Boolean
> includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061
>
> ----
--
> Version Information: Microsoft .NET Framework Version:2.0.50727.42;
> ASP.NET Version:2.0.50727.210
> I am pretty sure the problem has something to do with the fact that I am
> declaring the UserControl in my codebehind rather than my *.aspx file, but
> I am not quite sure what I need to do differently. If anyone can help me,
> I would appreciate it. Thanks.
> --
> Nathan Sokalski
> njsokalski@.hotmail.com
> http://www.nathansokalski.com/
>