Showing posts with label instance. Show all posts
Showing posts with label instance. Show all posts

Thursday, March 29, 2012

Object Persistence

I am trying to persist an instance specific object without using a session
object. Is this possible?

For example:
Class object: Car
Properties: Make, Model

Car.Make = Ford
Car.Model = F150

I would like to persist the object across postbacks without using a session
object. Or, if I do have to use a session object, what is the cleanest
mechinsim. Right now I save the object in the session after each property
change.Try using ViewState:

[Category("Data")]
[DefaultValue("")]
[Bindable(true)]
public Car SelectedCar
{
get
{
object c = ViewState["SelectedCar"];
return (c == null) ? new Car(): (Car)c;
}
set
{
ViewState["SelectedCar"] = value;
}
}
If you are talking a single page, ViewState is an option for persistence.
You can also create static variables, but you will have to key them to the
user. This means you either stick them in session or create your own
"session" mechanism. There are also other built in ASP.NET cache mechanism
(a search for "cache" and "asp.net" should yeield at least one article).

I would not be as fearful of session in ASP.NET as we were in traditional
ASP. It is far less dangerous, esp. if you think things through and only
store objects that have session scope.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

*************************************************
Think outside of the box!
*************************************************
"Robert" <Robert@.discussions.microsoft.comwrote in message
news:32474CC7-F9B8-416D-A679-3583FB994075@.microsoft.com...

Quote:

Originally Posted by

>I am trying to persist an instance specific object without using a session
object. Is this possible?
>
For example:
Class object: Car
Properties: Make, Model
>
Car.Make = Ford
Car.Model = F150
>
I would like to persist the object across postbacks without using a
session
object. Or, if I do have to use a session object, what is the cleanest
mechinsim. Right now I save the object in the session after each property
change.


Here are my views regarding your requirement

1. If the object is to be persisted across users think of Application objects
2. If the object is to be persisted across the pages for a user think of
session objects. If you are using ASP.NET 2.0 think of exploring Profile
Objects
3. If you want to persist the object across post back for a single page,
think of ViewState. ViewState has the limiation on amount of storage. If you
object is big ViewState might impact performance
4. If your object is big and you've performance consideration try DataCaching.
Data Caching persists user object on the IIS Memory. Data caching is similar
to Application objects. Data Caching cannot store too much of information.

Just analyze the above and figure out what's the best option for you...

"Robert" wrote:

Quote:

Originally Posted by

I am trying to persist an instance specific object without using a session
object. Is this possible?
>
For example:
Class object: Car
Properties: Make, Model
>
Car.Make = Ford
Car.Model = F150
>
I would like to persist the object across postbacks without using a session
object. Or, if I do have to use a session object, what is the cleanest
mechinsim. Right now I save the object in the session after each property
change.

object ref not set to an instance of an object

I am trying to run a sub in my class, my class imports ..

Imports BinaryIntellect.ZipUtils.ZipFileHelper

and my function is....

Public Sub saveScorm(ByVal source As String, ByVal destination As String)
Try
Dim paths = Server.MapPath("/ilearnscorm/")
paths = paths & "scormCourses/"
Dim ZipFileHelper As New BinaryIntellect.ZipUtils.ZipFileHelper
ExtractZipFile(source, paths & destination) 'unzip the files into directory
Catch ex As Exception
Throw ex.InnerException
End Try
End Sub

Any ideas?
ThanksAnd where is the exception thrown from?

Simple explanation of the "Object reference not set to an instance of an object" exception: it refers to a (class) variable that has not been instantiated - i.e. = New <something>. All you really need do is find that variable - which is where the stack trace helps significantly.

Hmm, you have a variable - ZipFileHelper - that is declared/instantiated but not used; why do you have it?

What's in the "ExtractZipFile" method? Relevant to the stack and debugging.

As you are doing nothing with the exception - just remove the try/catch. You're bubbling the exception (or more specifically the inner - never mind any useful information that may be included in the parent exception ;) ) anyway. This changes when you do something with the exception, for example logging it.
Here is my stack trace..
The extractZipFile method expects two parameters, the source and the destination directories

[NullReferenceException: Object reference not set to an instance of an object.]
_Default.btnSubmit_Click(Object sender, EventArgs e) +766
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102
If I create an instance I get ....
Access of shared member, constant member, enum member or nested type through an instance
If you look at the stack trace, you'll see that the first entry is "_Default.btnSubmit_Click(Object sender, EventArgs e) +766". This tells me that the exception occurred in your Default.aspx page, in the btnSubmit_Click event handler and that you're not running in debug mode.

So, change the solution build to Debug, deploy (if necessary), run the code again and check the line number that the stack trace gives you; it will be at the end of the line and will replace the "+766" part, e.g. "_Default.btnSubmit_Click(Object sender, EventArgs e) 123"
I'm willing to bet it's occurring inside the ExtractZipFile method. Step into it and watch where it fails in there.

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

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

Monday, March 26, 2012

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 message

hi folks, i've been getting this error message but i can't seem to figure out whats wrong

"object reference not set to an instance of an object"

here's the line it is refering to:

browserIDValue.Text = Membership.GetUser().ProviderUserKey.ToString()

any help would be great, thanks

It means, that the portion of your code Membership.GetUser().ProviderUserKey is comming up as nothing, so you cant do a .tostring on it

This function only works for the currently logged in user - and I think it gets a little funny if you are using windows authentication. Make sure you are logged in before you call the GetUser method, or specify which user you want to get in the GetUser(parms)


Check the following stuff:
if (Membership.GetUser() ==null && Membership.GetUser().ProviderUserKey ==null)throw new Exception("User is not logged in");Membership.GetUser().ProviderUserKey.ToString();

I guess that one of these two is available as the User is not authenticated.

Hope that helps,
Matthias :)


cheers guys, got that sorted, I'm having a similar promblem on another page where I'm inserting two rows into a table, I'm getting the same error as above when I attempt the second insert but the first insert works fine, its a bit confusing since they should be getting the same information, just the parameters swapped round

Protected Sub addFriend_ItemInserting(ByVal senderAs Object,ByVal eAs System.Web.UI.WebControls.DetailsViewInsertEventArgs)Handles addFriend.ItemInserting e.Values("userID_1") = Membership.GetUser().ProviderUserKey e.Values("userID_2") = Request.QueryString("userID")End SubProtected Sub getFriends_Inserted(ByVal senderAs Object,ByVal eAs System.Web.UI.WebControls.SqlDataSourceStatusEventArgs)Handles getFriends.InsertedDim DataSourceAs SqlDataSource =CType(FindControl("addFriend_2"), SqlDataSource)Dim userID_1 = Request.QueryString("userID")Dim userID_2 = Membership.GetUser().ProviderUserKey DataSource.InsertParameters.Add("userID_1", userID_1) DataSource.InsertParameters.Add("userID_2", userID_2) DataSource.Insert()End Sub

Always check whether a object exists (is instantiated) as explained before!

If you are sure you can use the object, access it. Otherwise you'll end up with quite a lot of those errors in bigger projects. NEVER assume a object is accessible.

Cheers,
Matthias :)

object reference is not set to an instance of object

con2.Open();

ls_sql ="SELECT business_partner_id , broker_flag FROM Application " +

"WHERE application_number =" +"'" +this.is_appno +"'";

SqlCommand cmd =newSqlCommand(ls_sql ,con2);

SqlDataAdapter sql =newSqlDataAdapter(cmd);

sql.Fill(DsTemp,"DtTemp");

I found error on strikethrough line " object reference is not set to an instance of object"

ls_sql ="SELECT point_score_ind FROM FP_Dealer WHERE financial_product_id = (SELECT financial_product_id" +

" FROM contract_detail WHERE application_number =" +"'" +this.is_appno +"'" +" AND identification_code = 1 ) " +

"AND business_partner_id = (SELECT business_partner_id FROM Application WHERE application_number =" +"'" +this.is_appno +"'" +" )" +

" AND role_cde =" +"'" + ls_role_code +"'";

cmd =newSqlCommand(ls_sql, con2);

cmd.CommandType =CommandType.Text;

sql =newSqlDataAdapter(cmd);

lc_point_score_ind = cmd.ExecuteScalar().ToString().

cmd.Connection.Close();

samq:

lc_point_score_ind = cmd.ExecuteScalar().ToString().

Hi,

Can you try to use

lc_point_score_ind = sql.SelectCommand.ExecuteScalar().ToString().

Hope this helps to solve your problem

Good LuckYes

Regards

Vineed

Object reference not set

Hi, the exception "Object reference not set to an instance of an object", was thrown when I run my code.

If Not IsPostBack Then

Dim DBConn As OdbcConnection
Dim DBCommand As OdbcDataAdapter
Dim i As Integer

For i = 0 To CarNamesDL.Items.Count - 1
If CarNamesDL.Items(i).Selected Then
DBConn = New OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=CarCompaniesDB;User=root;Password=soukpass;Option=3;")
DBCommand = New OdbcDataAdapter("SELECT CarID, Model From CarCompaniesDB where Make = '" & CarNamesDL.Items(i).Text & "'", DBConn)
Else : Exit For
End If
Next

DBCommand.Fill(DS, "CarCompaniesDB")

CarNamesDL.DataSource = DS.Tables("CarCompaniesDB").DefaultView

CarNamesDL.DataBind()

End If

This is the Source error:

Line 43: End If
Line 44: Next
Line 45: DBCommand.Fill(DS, "CarCompaniesDB")
Line 46:
Line 47: CarNames.DataSource = DS.Tables("CarCompaniesDB").DefaultView

I don't know what could be causing this. I don't think its because of notdeclaring a variable before its use 'cause I've checked. I'm not sureif its bad scoping, I've also made sure to Exit the For Loop

in the Else clause in case no match was found. Please take a look to see if my code is missing something or if it is incorrect, thank you in advance for yourhelp.

Hi,

Is your DS anywhere declared and new DataSet created and assigned to DS?

Even if your DS is declared somewhere else or not declared at all, you need to create new DataSet and assign it to DS variable.

DS = New DataSet()

-yuriy


please post complete post.

I dont see that you have initialize any where the "DS" that is DataSet.


Hi, thanks for your reply my code now sort of works but it still has a little problem. The following is my modified code:

If Not IsPostBack Then

Dim DBConn As OdbcConnection
Dim DBCommand As OdbcCommand
Dim i As Integer
Dim DS As New DataSet
For i = 0 To CarNamesDL.Items.Count - 1
If CarNamesDL.Items(i).Selected Then
DBConn = New OdbcConnection("Driver={MySQL ODBC 3.51Driver};Server=myServer;Database=CarCompaniesDB;User=myUser;Password=myPass;Option=3;")
DBCommand = New OdbcCommand("SELECT CarID, Model From CarCompaniesDBwhere Make = '" & CarNamesDL.Items(i).Text & "'", DBConn)

End If
Next
If Not IsNothing(DBConn) Then
DBConn.Open()
DBCommand.Connection = DBConn
Dim AD As New OdbcDataAdapter(DBCommand)

AD.Fill(DS, "CarCompaniesDB")
Me.CarNamesDL.DataTextField = "CarID"
Me.CarNamesDL.DataValueField = "Model"

CarNamesDL.DataBind()

End If
End If

Thisis the code for the button used to display the result, I don't quiteunderstand it since doing something different than what the MSDN saysits suppose to do.

Private Sub Bt_OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Bt_OK.Click
lblDataSelected.Text = "Selected Text: " &CarNamesDL.SelectedItem.Text & "<BR> Selected Value: " &CarNamesDL.SelectedValue & "<BR> Selected Index: " &CarNamesDL.SelectedIndex
End Sub

How do I get it to display make "Model" and not just the listitem when a user selects a listitem? Thank you for your help.

Object Reference not set

Hi

I am trying to compile an ASP.net project and I keep getting an error that says "Object Reference not set to an instance of an object" comming from the <Title> element

error:

Unable to start dbugging on the web server. <html>

<head>

<title>Object Reference not set to an instance of an object</title>

Source Code:

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%
Page.Response.Write("My Web Page")

%>
</div>
</form>
</body>
</html>

try a semicolon after your code.

Page.Response.Write("My Web Page");


Hi,

C# statements must end with a semicolon.

Regards,

dg_pp


I fixed it I had to use

aspnet_regiis.exe -i

Object Reference not set to an instance

I am getting this error: " Object Reference not set to an instance "

User Control Code

// returns DataSet
public SqlDataReader GetData()
{

SqlCommand myCommand = new SqlCommand("SELECT * FROM Categories",myConnection);

myCommand.CommandType = CommandType.Text;

myConnection.Open();
SqlDataReader dr = myCommand.ExecuteReader();
return dr;

}
<code
Aspx Page Code

<code
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
WebUserControl1 wc = new WebUserControl1();
myDataGrid.DataSource = wc.GetData();
myDataGrid.DataBind();

}
}

Where u have defined myConnection object?

Is it accessible in public SqlDataReader GetData() function?
Where ismyconnection variable declared and instantiated? It is the suspect because I don't see its declaratiion and instantiation in the local scope of GetData method.
Hi,

Well I draged and Dropped the myConnection object from the ToolBox. Which I guess makes it protected ? Is this wrong ?

Object reference not set to an instance

Hi,

I'm getting

'Object reference not set to an instance of an object' error when I have


Dim lblEnterNew As System.Web.UI.WebControls.Label

If DataGrid1.EditItemIndex > -1 Then
lblEnterNew.Visible = False
Else
lblEnterNew.Visible = True
End If

and my control in the page is


<asp:Label id="lblEnterNew" runat="server" class="dept"></asp:Label>

Any idea why I'm getting this error?Are you sure that the error occurs on the label? The label looks ok to me.
You are getting the error because you are dim-ing an instance of a label in a variable at the same time it is probably already dimmed in the hidden code-behind in the '#Region " Web Form Designer Generated Code " ' region. You would probably not get the error if you dimmed it wit the New statement "Dim lblEnterNew as New System.Web.UI.WebControls.Label" but then you would have problems referencing the actual control on the web page.

Try removing the "Dim lblEnterNew as System.Web.UI.WebControls.Label" line from the code as this should fix the problem and there should be a statement similiar to: "Protected Withevents lblEnterNew as Label" near the top of the code behind page already.
That worked. Should all of my controls be dimmed in the '#Region' but not variables?
All controls which you create in the design mode of Visual Studio are automatically dimed in the #Region section. You can define your own variables just after the class has started!

Object reference not set to an instance of an object

I am having a problem with a page that I am trying to develop=2E I=
am new at asp=2Enet=2E
The page I have created makes a datagrid that has two links a=
edit and a cancel link=2E When you click either of the links it=
throws the following error "Object reference noet set to an=
instance of an object=2E The following lines appear along with=
that error message
Line 69: Dim CurrentTextBox As=
System=2EWeb=2EUI=2EWebControls=2ETextbo
x
Line 70: CurrentTextBox=3DE=2EItem=2EFindControl(
"edit_" &=
Cols(I))
Line 71: Dim ColValue As String =3D CurrentTextBox=2EText
Line 72: MyCommand=2EParameters("@dotnet.itags.org." &=
Cols(I))=2EValue=3DColValue
Line 73: Next
I forgot to mention that this is part of a For Next Loop
What could be causing this--I can post more code if needed
Thank you in advance
Max
--
From: Max Gay
Posted by a user from =2ENET 247 (http://www=2Edotnet247=2Ecom/)
<Id>2jeCOwwgHEGeAglBD0PF4Q=3D=3D</Id>Okay, Max, let's walk through this, and see what the possible candidates
are. In case you're not sure, this exception means that you've tried to
treat some variable that is null (Nothing) as an object of the type that you
thought it was.
Line 69: Dim CurrentTextBox As System.Web.UI.WebControls.Textbox
This line declares a variable. There is no object reference here, only a
type reference.
Line 70: CurrentTextBox=E.Item.FindControl("edit_" & Cols(I))
This line assigns the result of the FindControl method to your variable. It
could not throw an exception, because if the object is not found, the method
returns null (Nothing). That is a valid value for any object variable.
Line 71: Dim ColValue As String = CurrentTextBox.Text
This is a very likely candidate. You can't treat Nothing like a TextBox. It
has no TextBox properties. In fact, it has no properties at all. However,
there is one other possibility:
Line 72: MyCommand.Parameters("@." & Cols(I)).Value=ColValue
If MyCommand is Nothing, or MyCommand.Parameters is Nothing, or
MyCommand.Parameters("@." & Cols(i)) is Nothing, this could also be the
offending line.
HTH,
Kevin Spencer
Microsoft MVP
.Net Developer
Ambiguity has a certain quality to it.
"Max Gay via .NET 247" <anonymous@.dotnet247.com> wrote in message
news:OMA8PEsaFHA.1088@.TK2MSFTNGP14.phx.gbl...
I am having a problem with a page that I am trying to develop. I am new at
asp.net.
The page I have created makes a datagrid that has two links a edit and a
cancel link. When you click either of the links it throws the following
error "Object reference noet set to an instance of an object. The following
lines appear along with that error message
Line 69: Dim CurrentTextBox As System.Web.UI.WebControls.Textbox
Line 70: CurrentTextBox=E.Item.FindControl("edit_" & Cols(I))
Line 71: Dim ColValue As String = CurrentTextBox.Text
Line 72: MyCommand.Parameters("@." & Cols(I)).Value=ColValue
Line 73: Next
I forgot to mention that this is part of a For Next Loop
What could be causing this--I can post more code if needed
Thank you in advance
Max
--
From: Max Gay
Posted by a user from .NET 247 (http://www.dotnet247.com/)
<Id>2jeCOwwgHEGeAglBD0PF4Q==</Id>

Object reference not set to an instance of an object

Hello all
This is normally an easy error to fix.
The creation of the object was done correclty.
I have an object that I am using and have been using. Suddenly yesterday I
get this error using it.
I have inregistered the DLL deleted the DLL and copied it from the source
and then re-registered it. Same issue.
I removed the reference from my web app and then added the reference back,
same issue.
Its like the function ParseString has an object in it that isn't being
created properly ... but this worked yesterday just fine.
Until I changed from using an UPDATE query to using a stored procedure
(which should have no berring at all).
I'm stumped. Any ideas at all would be greatly helpful.
Thanks
Jon
Here is the code:
' find the dictations edited in the portal, clean the HTML just
incase it has MS Word stuff in it.
Dim cn As New
SqlConnection(ConfigurationSettings.AppSettings("RepositoryConnectionString"
))
Dim cn1 As New
SqlConnection(ConfigurationSettings.AppSettings("RepositoryConnectionString"
))
cn.Open()
cn1.Open()
Dim TidyDOC As Tidy.Document (THIS IS THE OBJECT I AM USING)
**************************
Dim eCode As Int16
Dim newTranscript As String
Dim cmdGetDictations As New SqlCommand("select patientdictationid,
isnull(transcript,'') as transcript from tblPatientDictation where
PortalEdit=1", cn)
Dim rdrGetDictations As SqlDataReader =
cmdGetDictations.ExecuteReader
Dim cmdWriteDictation As SqlCommand
Dim intResult As Int16
Dim DictText As String
Dim UpdateCount As Int16
Do While rdrGetDictations.Read
TidyDOC = New Tidy.Document <-- i do a NEW to create
the object
Try
DictText = rdrGetDictations("transcript")
TidyDOC.SetOptBool(TidyATL.TidyOptionId.TidyWord2000, 1)
TidyDOC.SetOptBool(TidyATL.TidyOptionId.TidyHtmlOut, 1)
eCode = TidyDOC.ParseString(DictText) <-- i
get the obj ref not set here. .. after its been ref twice before this line
..
eCode = TidyDOC.CleanAndRepair
TidyDOC.SetOptBool(TidyATL.TidyOptionId.TidyForceOutput, 1)
newTranscript = TidyDOC.SaveString
newTranscript = newTranscript.Replace("'", "''")
newTranscript = newTranscript.Replace(Chr(34), "''")
cmdWriteDictation = New SqlCommand("spUpdateDictation", cn1)
cmdWriteDictation.CommandType = CommandType.StoredProcedure
cmdWriteDictation.Parameters.Add("@dotnet.itags.org.Dictation",
newTranscript)
cmdWriteDictation.Parameters.Add("@dotnet.itags.org.DictationID",
rdrGetDictations("patientdictationid"))
intResult = cmdWriteDictation.ExecuteNonQuery
cmdWriteDictation.Dispose()
UpdateCount += 1
Catch ex As Exception
Exit Do
End Try
TidyDOC = Nothing
Loop
cmdGetDictations.Dispose()
cmdGetDictations = Nothing
rdrGetDictations.Close()
rdrGetDictations = Nothing
cmdWriteDictation = Nothing
cn.Close()
cn = Nothing
cn1.Close()
cn1 = Nothing
lblUserMessage.Text = "updated : " & UpdateCount
lblUserMessage.Visible = True
We are experiencing a similar problem with the data reader. We found
this post on the MSDN forums that sounds related.
[url]http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=137373&SiteID=1&PageID=1[/ur
l]
It happens randomly, but once it starts our app quickly falls off a
cliff and we have to reset the servers. We are currently trying turning
off connection pooling which is at best a temp solution. Our
performance requirements won't support this as a long term solution.
Worth a try.
Thank you for the reply and the link ... i'll check it out.
"rsk7" <rkopitzke@.earthlink.net> wrote in message
news:1160089580.961072.241760@.k70g2000cwa.googlegroups.com...
>
> We are experiencing a similar problem with the data reader. We found
> this post on the MSDN forums that sounds related.
> [url]http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=137373&SiteID=1&PageID=1[/
url]
> It happens randomly, but once it starts our app quickly falls off a
> cliff and we have to reset the servers. We are currently trying turning
> off connection pooling which is at best a temp solution. Our
> performance requirements won't support this as a long term solution.
> Worth a try.
>

object reference not set to an instance of an object

Hello all, I have this problem in this code I am studying.
I'm getting this error saying that Server Error 'in
'/mcsdWebApps/Chapter5/DBruntime' Application.
Object reference not set to an instance of an object. It says the error is
on line 39 which is
Dim rowInsert As DataRow = dsContacts.Tables("Contacts").NewRow
Thanks in advance for any help!
Here is the full code:
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e as System.EventArgs) Handles MyBase.Load
'1. Create the data connection.
Dim ContactMgmt As New SqlConnection _
(" Server=(local);database=Contacts;Trusted
_Connection=yes")
'Create an adapter.
Dim adptContactMgmt As New _
SqlDataAdapter("select * from Contacts", ContactMgmt)
'2. Create a data set.
Dim dsContacts As New DataSet()
'Set select command.
adptContactMgmt.SelectCommand.CommandText = _
"SELECT * FROM Contacts"
'3. Create, insert, delete, and update commands automatically.
Dim cmdContactMgmt As SqlCommandBuilder = New _
SqlCommandBuilder(adptContactMgmt)
'4. Create a new row.
'HERE'S WHERE I'M GETTING THE ERROR!
Dim rowInsert as DataRow = dsContacts.Tables("Contacts").NewRow
'Add data to fields in the row.
rowInsert("ContactId") = 3
rowInsert("FirstName") = "Mary"
rowInsert("LastName") = "Smith"
rowInsert("WorkPhone") = "(444) 222-2222"
'Add the row to the data set.
dsContacts.Tables("Contacts").Rows.Add(rowInsert)
'5. Update the database.
adptContactMgmt.Update(dsContacts.Tables("Contacts"))
End SubHi,
The problem is that you have not filled your dataset so the dataset does not
have a table called Contacts.
Here is a modified version of the code that should get you going.
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e as System.EventArgs) Handles MyBase.Load
'1. Create the data connection.
Dim ContactMgmt As New SqlConnection _
(" Server=(local);database=Contacts;Trusted
_Connection=yes")
'Create an adapter.
Dim adptContactMgmt As New _
SqlDataAdapter("select * from Contacts", ContactMgmt)
'2. Create a data set.
Dim dsContacts As New DataSet()
'Set select command. This is not needed since this was set when you
constructed the SqlDataAdapter
'3. Create, insert, delete, and update commands automatically.
Dim cmdContactMgmt As SqlCommandBuilder = New _
SqlCommandBuilder(adptContactMgmt)
'*** The missing part, Fill the dataset using the DataAdapter and pass the
table name that you want
' the DataAdapter to use.
adptContactMgmt.Fill(dsContacts, "Contacts")
'4. Create a new row.
Dim rowInsert as DataRow = dsContacts.Tables("Contacts").NewRow
'Add data to fields in the row.
rowInsert("ContactId") = 3
rowInsert("FirstName") = "Mary"
rowInsert("LastName") = "Smith"
rowInsert("WorkPhone") = "(444) 222-2222"
'Add the row to the data set.
dsContacts.Tables("Contacts").Rows.Add(rowInsert)
'5. Update the database.
adptContactMgmt.Update(dsContacts.Tables("Contacts"))
End Sub
Hope this helps
Chris Taylor
http://dotnetjunkies.com/weblog/chris.taylor
"student" <mr_chat123@.yahoo.com> wrote in message
news:24HBd.9293$by5.9098@.newssvr19.news.prodigy.com...
> Hello all, I have this problem in this code I am studying.
> I'm getting this error saying that Server Error 'in
> '/mcsdWebApps/Chapter5/DBruntime' Application.
> Object reference not set to an instance of an object. It says the error is
> on line 39 which is
> Dim rowInsert As DataRow = dsContacts.Tables("Contacts").NewRow
> Thanks in advance for any help!
> Here is the full code:
> Private Sub Page_Load(ByVal sender As System.Object, _
> ByVal e as System.EventArgs) Handles MyBase.Load
> '1. Create the data connection.
> Dim ContactMgmt As New SqlConnection _
> (" Server=(local);database=Contacts;Trusted
_Connection=yes")
> 'Create an adapter.
> Dim adptContactMgmt As New _
> SqlDataAdapter("select * from Contacts", ContactMgmt)
> '2. Create a data set.
> Dim dsContacts As New DataSet()
> 'Set select command.
> adptContactMgmt.SelectCommand.CommandText = _
> "SELECT * FROM Contacts"
> '3. Create, insert, delete, and update commands automatically.
> Dim cmdContactMgmt As SqlCommandBuilder = New _
> SqlCommandBuilder(adptContactMgmt)
> '4. Create a new row.
> 'HERE'S WHERE I'M GETTING THE ERROR!
> Dim rowInsert as DataRow = dsContacts.Tables("Contacts").NewRow
> 'Add data to fields in the row.
> rowInsert("ContactId") = 3
> rowInsert("FirstName") = "Mary"
> rowInsert("LastName") = "Smith"
> rowInsert("WorkPhone") = "(444) 222-2222"
> 'Add the row to the data set.
> dsContacts.Tables("Contacts").Rows.Add(rowInsert)
> '5. Update the database.
> adptContactMgmt.Update(dsContacts.Tables("Contacts"))
> End Sub
>
Thanks for the help that got rid of the error, only now I'm getting a blank
screen when I view the code in a browser Internet Explorer, any idea as to
what is causing this'
thanks,
student
"Chris Taylor" <chris_taylor_za@.hotmail.com> wrote in message
news:%23TeGJtG8EHA.2700@.TK2MSFTNGP14.phx.gbl...
> Hi,
> The problem is that you have not filled your dataset so the dataset does
not
> have a table called Contacts.
> Here is a modified version of the code that should get you going.
> Private Sub Page_Load(ByVal sender As System.Object, _
> ByVal e as System.EventArgs) Handles MyBase.Load
> '1. Create the data connection.
> Dim ContactMgmt As New SqlConnection _
> (" Server=(local);database=Contacts;Trusted
_Connection=yes")
> 'Create an adapter.
> Dim adptContactMgmt As New _
> SqlDataAdapter("select * from Contacts", ContactMgmt)
> '2. Create a data set.
> Dim dsContacts As New DataSet()
> 'Set select command. This is not needed since this was set when you
> constructed the SqlDataAdapter
> '3. Create, insert, delete, and update commands automatically.
> Dim cmdContactMgmt As SqlCommandBuilder = New _
> SqlCommandBuilder(adptContactMgmt)
> '*** The missing part, Fill the dataset using the DataAdapter and pass
the
> table name that you want
> ' the DataAdapter to use.
> adptContactMgmt.Fill(dsContacts, "Contacts")
> '4. Create a new row.
> Dim rowInsert as DataRow = dsContacts.Tables("Contacts").NewRow
> 'Add data to fields in the row.
> rowInsert("ContactId") = 3
> rowInsert("FirstName") = "Mary"
> rowInsert("LastName") = "Smith"
> rowInsert("WorkPhone") = "(444) 222-2222"
> 'Add the row to the data set.
> dsContacts.Tables("Contacts").Rows.Add(rowInsert)
> '5. Update the database.
> adptContactMgmt.Update(dsContacts.Tables("Contacts"))
> End Sub
>
> Hope this helps
> --
> Chris Taylor
> http://dotnetjunkies.com/weblog/chris.taylor
> "student" <mr_chat123@.yahoo.com> wrote in message
> news:24HBd.9293$by5.9098@.newssvr19.news.prodigy.com...
is
>
Hi,
I do not see what data control you are using, but one thing with ASP.NET is
that once you have setup the databinding you have to call DataBind()
otherwise no binding happens.
Hope this helps
Chris Taylor
http://dotnetjunkies.com/weblog/chris.taylor
"student" <mr_chat123@.yahoo.com> wrote in message
news:ZQ_Bd.9661$by5.495@.newssvr19.news.prodigy.com...
> Thanks for the help that got rid of the error, only now I'm getting a
blank
> screen when I view the code in a browser Internet Explorer, any idea as to
> what is causing this'
> thanks,
> student
> "Chris Taylor" <chris_taylor_za@.hotmail.com> wrote in message
> news:%23TeGJtG8EHA.2700@.TK2MSFTNGP14.phx.gbl...
> not
> the
error
> is
>