Showing posts with label run. Show all posts
Showing posts with label run. Show all posts

Thursday, March 29, 2012

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.

Monday, March 26, 2012

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 to an instance of an object

hi there,
I looked up posts on how to get a javascript confirm on the onclick of a
button to determine whether to run server code and i wrote this on the page
load..
string jsalert = "java script:if(confirm ('Is the employee a rehire?') ==
false) return false";
btnEdit.Attributes["onclick"]=jsalert;
however I'm getting the error message in my subject heading. what have i
done wrong? when i start to write it i get intellisense so i know it
recognises btnEdit.Hi,
Make sure in your HTML that your id tag is exactly "btnEdit" with the
correct case. You receive it in intellisense because it is declared in your
code behind which doesn't necessarily mean it is in your .aspx file. Good
luck! Ken.
Ken Dopierala Jr.
For great ASP.Net web hosting try:
http://www.webhost4life.com/default.asp?refid=Spinlight
If you sign up under me and need help, email me.
"louise raisbeck" <louiseraisbeck@.discussions.microsoft.com> wrote in
message news:25C2CE14-0C92-41CC-B349-4F82055E0336@.microsoft.com...
> hi there,
> I looked up posts on how to get a javascript confirm on the onclick of a
> button to determine whether to run server code and i wrote this on the
page
> load..
> string jsalert = "java script:if(confirm ('Is the employee a rehire?') ==
> false) return false";
> btnEdit.Attributes["onclick"]=jsalert;
> however I'm getting the error message in my subject heading. what have i
> done wrong? when i start to write it i get intellisense so i know it
> recognises btnEdit.
Try the following:
btnEdit.Attributes.Add("onclick", jsalert);
HTH,
Kevin Spencer
.Net Developer
Microsoft MVP
Neither a follower
nor a lender be.
"louise raisbeck" <louiseraisbeck@.discussions.microsoft.com> wrote in
message news:25C2CE14-0C92-41CC-B349-4F82055E0336@.microsoft.com...
> hi there,
> I looked up posts on how to get a javascript confirm on the onclick of a
> button to determine whether to run server code and i wrote this on the
page
> load..
> string jsalert = "java script:if(confirm ('Is the employee a rehire?') ==
> false) return false";
> btnEdit.Attributes["onclick"]=jsalert;
> however I'm getting the error message in my subject heading. what have i
> done wrong? when i start to write it i get intellisense so i know it
> recognises btnEdit.
hiya. yes. its as btnEdit in both my aspx, my declarations and my code ?
"Ken Dopierala Jr." wrote:

> Hi,
> Make sure in your HTML that your id tag is exactly "btnEdit" with the
> correct case. You receive it in intellisense because it is declared in yo
ur
> code behind which doesn't necessarily mean it is in your .aspx file. Good
> luck! Ken.
> --
> Ken Dopierala Jr.
> For great ASP.Net web hosting try:
> http://www.webhost4life.com/default.asp?refid=Spinlight
> If you sign up under me and need help, email me.
> "louise raisbeck" <louiseraisbeck@.discussions.microsoft.com> wrote in
> message news:25C2CE14-0C92-41CC-B349-4F82055E0336@.microsoft.com...
> page
>
>
yes i did actually try that syntax. same error message:
System.NullReferenceException: Object reference not set to an instance of an
object
"louise raisbeck" wrote:

> hi there,
> I looked up posts on how to get a javascript confirm on the onclick of a
> button to determine whether to run server code and i wrote this on the pag
e
> load..
> string jsalert = "java script:if(confirm ('Is the employee a rehire?') ==
> false) return false";
> btnEdit.Attributes["onclick"]=jsalert;
> however I'm getting the error message in my subject heading. what have i
> done wrong? when i start to write it i get intellisense so i know it
> recognises btnEdit.
Hi,
Do you have the runat="server" tag in your btnEdit? Also, where and when
are you getting the error? Are you sure it happens on the
btnEdit.Attributes line? Also I would definitely switch your syntax to what
Kevin showed, that's how I've always done it. Try commenting out the
attributes line and do something else with the button. Like btnEdit.Visible
= True, if this gives you the same error then there is a problem with either
your button tag or your button declaration, if no error then we have
narrowed it down to how you are adding your attribute. Good luck! Ken.
Ken Dopierala Jr.
For great ASP.Net web hosting try:
http://www.webhost4life.com/default.asp?refid=Spinlight
If you sign up under me and need help, email me.
"louise raisbeck" <louiseraisbeck@.discussions.microsoft.com> wrote in
message news:3728851E-41F0-4369-81A1-6181B8FFA60D@.microsoft.com...
> yes i did actually try that syntax. same error message:
> System.NullReferenceException: Object reference not set to an instance of
an
> object
> "louise raisbeck" wrote:
>
page
Well, Louise, you have 2 possibilities:
btnEdit is Null;
btnEdit.Attributes is null;
What exactly IS "btnEdit?"
--
HTH,
Kevin Spencer
.Net Developer
Microsoft MVP
Neither a follower
nor a lender be.
"louise raisbeck" <louiseraisbeck@.discussions.microsoft.com> wrote in
message news:3728851E-41F0-4369-81A1-6181B8FFA60D@.microsoft.com...
> yes i did actually try that syntax. same error message:
> System.NullReferenceException: Object reference not set to an instance of
an
> object
> "louise raisbeck" wrote:
>
page

Saturday, March 24, 2012

object reference not set to an instance of an object

hi there,

I looked up posts on how to get a javascript confirm on the onclick of a
button to determine whether to run server code and i wrote this on the page
load..

string jsalert = "javascript:if(confirm ('Is the employee a rehire?') ==
false) return false";
btnEdit.Attributes["onclick"]=jsalert;

however I'm getting the error message in my subject heading. what have i
done wrong? when i start to write it i get intellisense so i know it
recognises btnEdit.Hi,

Make sure in your HTML that your id tag is exactly "btnEdit" with the
correct case. You receive it in intellisense because it is declared in your
code behind which doesn't necessarily mean it is in your .aspx file. Good
luck! Ken.

--
Ken Dopierala Jr.
For great ASP.Net web hosting try:
http://www.webhost4life.com/default.asp?refid=Spinlight
If you sign up under me and need help, email me.

"louise raisbeck" <louiseraisbeck@.discussions.microsoft.com> wrote in
message news:25C2CE14-0C92-41CC-B349-4F82055E0336@.microsoft.com...
> hi there,
> I looked up posts on how to get a javascript confirm on the onclick of a
> button to determine whether to run server code and i wrote this on the
page
> load..
> string jsalert = "javascript:if(confirm ('Is the employee a rehire?') ==
> false) return false";
> btnEdit.Attributes["onclick"]=jsalert;
> however I'm getting the error message in my subject heading. what have i
> done wrong? when i start to write it i get intellisense so i know it
> recognises btnEdit.
Try the following:

btnEdit.Attributes.Add("onclick", jsalert);

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

"louise raisbeck" <louiseraisbeck@.discussions.microsoft.com> wrote in
message news:25C2CE14-0C92-41CC-B349-4F82055E0336@.microsoft.com...
> hi there,
> I looked up posts on how to get a javascript confirm on the onclick of a
> button to determine whether to run server code and i wrote this on the
page
> load..
> string jsalert = "javascript:if(confirm ('Is the employee a rehire?') ==
> false) return false";
> btnEdit.Attributes["onclick"]=jsalert;
> however I'm getting the error message in my subject heading. what have i
> done wrong? when i start to write it i get intellisense so i know it
> recognises btnEdit.
hiya. yes. its as btnEdit in both my aspx, my declarations and my code ?

"Ken Dopierala Jr." wrote:

> Hi,
> Make sure in your HTML that your id tag is exactly "btnEdit" with the
> correct case. You receive it in intellisense because it is declared in your
> code behind which doesn't necessarily mean it is in your .aspx file. Good
> luck! Ken.
> --
> Ken Dopierala Jr.
> For great ASP.Net web hosting try:
> http://www.webhost4life.com/default.asp?refid=Spinlight
> If you sign up under me and need help, email me.
> "louise raisbeck" <louiseraisbeck@.discussions.microsoft.com> wrote in
> message news:25C2CE14-0C92-41CC-B349-4F82055E0336@.microsoft.com...
> > hi there,
> > I looked up posts on how to get a javascript confirm on the onclick of a
> > button to determine whether to run server code and i wrote this on the
> page
> > load..
> > string jsalert = "javascript:if(confirm ('Is the employee a rehire?') ==
> > false) return false";
> > btnEdit.Attributes["onclick"]=jsalert;
> > however I'm getting the error message in my subject heading. what have i
> > done wrong? when i start to write it i get intellisense so i know it
> > recognises btnEdit.
>
yes i did actually try that syntax. same error message:

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

"louise raisbeck" wrote:

> hi there,
> I looked up posts on how to get a javascript confirm on the onclick of a
> button to determine whether to run server code and i wrote this on the page
> load..
> string jsalert = "javascript:if(confirm ('Is the employee a rehire?') ==
> false) return false";
> btnEdit.Attributes["onclick"]=jsalert;
> however I'm getting the error message in my subject heading. what have i
> done wrong? when i start to write it i get intellisense so i know it
> recognises btnEdit.
Hi,

Do you have the runat="server" tag in your btnEdit? Also, where and when
are you getting the error? Are you sure it happens on the
btnEdit.Attributes line? Also I would definitely switch your syntax to what
Kevin showed, that's how I've always done it. Try commenting out the
attributes line and do something else with the button. Like btnEdit.Visible
= True, if this gives you the same error then there is a problem with either
your button tag or your button declaration, if no error then we have
narrowed it down to how you are adding your attribute. Good luck! Ken.

--
Ken Dopierala Jr.
For great ASP.Net web hosting try:
http://www.webhost4life.com/default.asp?refid=Spinlight
If you sign up under me and need help, email me.

"louise raisbeck" <louiseraisbeck@.discussions.microsoft.com> wrote in
message news:3728851E-41F0-4369-81A1-6181B8FFA60D@.microsoft.com...
> yes i did actually try that syntax. same error message:
> System.NullReferenceException: Object reference not set to an instance of
an
> object
> "louise raisbeck" wrote:
> > hi there,
> > I looked up posts on how to get a javascript confirm on the onclick of a
> > button to determine whether to run server code and i wrote this on the
page
> > load..
> > string jsalert = "javascript:if(confirm ('Is the employee a rehire?') ==
> > false) return false";
> > btnEdit.Attributes["onclick"]=jsalert;
> > however I'm getting the error message in my subject heading. what have i
> > done wrong? when i start to write it i get intellisense so i know it
> > recognises btnEdit.
Well, Louise, you have 2 possibilities:

btnEdit is Null;
btnEdit.Attributes is null;

What exactly IS "btnEdit?"
--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Neither a follower
nor a lender be.

"louise raisbeck" <louiseraisbeck@.discussions.microsoft.com> wrote in
message news:3728851E-41F0-4369-81A1-6181B8FFA60D@.microsoft.com...
> yes i did actually try that syntax. same error message:
> System.NullReferenceException: Object reference not set to an instance of
an
> object
> "louise raisbeck" wrote:
> > hi there,
> > I looked up posts on how to get a javascript confirm on the onclick of a
> > button to determine whether to run server code and i wrote this on the
page
> > load..
> > string jsalert = "javascript:if(confirm ('Is the employee a rehire?') ==
> > false) return false";
> > btnEdit.Attributes["onclick"]=jsalert;
> > however I'm getting the error message in my subject heading. what have i
> > done wrong? when i start to write it i get intellisense so i know it
> > recognises btnEdit.

Thursday, March 22, 2012

Object reference not set to an instance of an object Error

I receive the above error when I run my asp.net Application. I can't see where the mistake is and it's driving me nuts. I'm new to this and any pointing in the right direction is greatly appreciated.

line 58 throws the error

Line 56: If bSwitch Then
Line 57: ' Get the text.
Line 58: EncryptClass.Text = txtSource.Text
Line 59: EncryptClass.Encrypt()
Line 60:

The codebehind for the form is.

Public Class WebForm1
Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

Dim EncryptClass As EncryptorClass

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

' The first time this page is displayed
If Not IsPostBack Then
' Create a new Encryptor object.
EncryptClass = New EncryptorClass
' Store the object in a Session state variable.
Session("EncryptClass") = EncryptClass
Else
' Get the Session EncryptClass variable.
EncryptClass = Session("EncryptClass")
End If

End Sub

Private Sub btnEncrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEncrypt.Click
' Declare a boolean switch.
Dim bSwitch As Boolean

' Get the value from ViewState and switch it.
bSwitch = Not Viewstate("bSwitch")

' Save the new value in ViewState.
ViewState("bSwitch") = bSwitch

' Use the switch to either Encrypt or restore the text in TextBox1.
If bSwitch Then
' Get the text.
EncryptClass.Text = txtSource.Text
EncryptClass.Encrypt()

' (1) Encrypt it – use the method you developed for the EncryptClass
' (2) Display the text in the textbox
' (3) Change the Button text to say "Restore"
'
txtSource.Text = EncryptClass.Text
btnEncrypt.Text = "Restore"
Else

' (1) Restore the original text – use the method you developed for the EncryptClass
' (2) Display the text in the textbox
'(3) Change the Button text to say "Encrypt"

EncryptClass.Restore()
txtSource.Text = EncryptClass.Text
btnEncrypt.Text = "Encrypt"
End If

End Sub
End Class

Here is the class that I created:

Imports System.Security.Cryptography

Friend Class EncryptorClass
Private mstrText As String
Private mstrOriginal As String

'contols the access to the module-level variables
Public Property Text() As String
Get
Text = mstrText
End Get
Set(ByVal Value As String)
mstrText = Value
' Keep a copy of the original for Restore.
mstrOriginal = Value
End Set
End Property

' Restores Encrypted text back to the original.
Public Sub Restore()
mstrText = mstrOriginal
End Sub

Public Sub Encrypt()

Dim byteArray As Byte()

Dim textEncoder As New System.Text.ASCIIEncoding

'(1) Convert string -> byte array
' use the ASCIIEncoding Class's GetBytes() method to convert the mstrText string, and save the value in the byteArray variable */
byteArray = textEncoder.GetBytes(mstrText)

'(2) Convert byte array to SHA1 hash
Dim result() As Byte
Dim shaM As New SHA512Managed
' use the SHA512Managed Class's ComputeHash() method to convert the byteArray, and save the value in the result variable */
result = shaM.ComputeHash(byteArray)

'(3) Convert byte array to hexadecimal string
Dim hexString As String = ""
Dim i As Integer = 0
Dim intArraySize = result.Length

'Loop thru the "result" Byte Array, and convert each byte into the its hexadecimal value
'The property result.Length will give you the size of the result array, remember that arrays are zero-based.
'To convert a byte into hexadecimal, use the Hex() function.
'Remember to concatenate each value as you convert it, to the previous one in the string.
'When you are done, save the hexString to the mstrText variable, so it can be used by the web form.

While i < intArraySize
hexString = hexString & Hex(result(i))
End While

mstrText = hexString
End Sub
End Class

Thanks,

DigitalDraculaTry changing the following in your else clause of If Not PostBack


EncryptClass = Session("EncryptClass")

to

EncryptClass = CType(Session("EncryptClass"), EncryptorClass)

Kumar,

I changed it but it makes no difference. That code would only be called after subsequent calls. The problem lies in the intial call "IsNotPostback".
Thanks for the assist. I'm still hammering away at it.

Mark
What do you mean the problem lies in the initial call. At what point of time you are getting this error? When the user clicks the button, or when the page loads for the first time?
Are you importing the dll that contains your custom class somewhere?
Kumar,

I'm sorry. The error is thrown after the user clicks the "Encrypt" button.
I meant to say that the problem lies when the object is to be initially instantiated, which occurs on the click event.
It's not even coming up the first time. I anticipate that if the object is successfully instantiated then on the second and subsequent button clicks the session object will be available.
Sorry for any confusion. I'm new to this.

Mark
Martin,

The custom class was creates and is listed in the project solution so I was under the impression that I could just use it. Do I need to import the class, and if so how would I do it, with the "Imports" statement at the top of my webform?
Thanks for the help. I really appreciate it.

Mrk
Well, I only use notepad. So, I am unfamiliar with your IDE. But, the page that uses your class should have a statement something like -

<%@. Register TagPrefix="AnyNameYouLike" NameSpace="TheNamespaceDeclaredInYourClassFile" Assembly="TheNameOfTheCompiledDllWithoutTheDllExtension" %>
Then you use the class either as
<script>Sub someSub()
Dim x as New YourClass()
...
End Sub
</script>
or
<html><body>
<AnyNameYouLike:YourClass runat="server"/>
</body></html>
Cheers
Martin

Object reference not set to an instance of an object HELP!

i get this server error when i try to run httpwriter. Can anyone help? i'm trying to run a string of html codings to open in current/new window. Not sure if this is able to work though..

Object reference not set to an instance of an object

Line 151: HTP.Write(x);

C# file

part of CODE:

publicclass test2 : System.Web.UI.Page

{

protected System.Web.UI.WebControls.Button BTNClick;

protectedSystem.Web.HttpWriter Writer;

}

...

privatevoid BTNClick_Click(object sender, System.EventArgs e)

{

string x =@dotnet.itags.org."...ssssss"

Writer.write(x);

}

...

i get this error sometimes when i do not create an instance from the class for example

Dim a as ClassName()

a.print()

this is where i have problem!!!

but if you do

Dim a as New ClassName()

a.print()

That will be fine as i have created new instance by saying "New" key word... but notice that this message error is not always mean this !!! so try that and let me know !


This does not create an HttpWriter
protected System.Web.HttpWriter Writer;
It only declares one. In fact, just do this as you've already got an instance of an HttpWriter built into the Page class.

private void BTNClick_Click(object sender, System.EventArgs e)
{
string x=@."...ssssss"

Response.Write(x);
}

NC...

Object reference not set to an instance of an object.

I keep receiving "Object reference not set to an instance of an object" error when trying to run this code:

Private Sub cmdok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdok.Click
Dim rs1 As SqlClient.SqlDataAdapter
Dim ds As DataSet
Dim xnav As String
Dim xfreq As String
Dim xsn As String
Dim xfw As String
Dim xdte As Date
Dim xrecvd As String
Dim xrels As String
Dim xremarks As String
Dim xcmpy As String
Dim xrver As String
Dim xplate As String
Dim xdr As String
Dim xassign As Date
Dim msg As String

If TXTsn.Text <> "" Then

Dim conPubs As New SqlConnection(ConfigurationSettings.AppSettings("connectionString"))
rs1 = New SqlClient.SqlDataAdapter("SELECT * FROM tbl_Inbox WHERE imd_sn = '" & TXTsn.Text & "'", conPubs)

ds = New DataSet
rs1.Fill(ds, "imd_nav")

If ds.Tables(0).Rows.Count <> 0 Then
xrels = ds.Tables(0).Rows(0)("imd_rels").ToString()
xrecvd = ds.Tables(0).Rows(0)("imd_recvd").ToString()

Functions.InsertImdAssign(TXTnav.Text, TXTfreq.Text, TXTsn.Text, TXTfw.Text, TXTdate.Text, xrecvd, xrels, TXTremarks.Text, TXTcmpy.Text, TXTrver.Text, TXTplate.Text, TXTdr.Text, TXTassign.Text)

conPubs.Close()
End If

End If
End Sub

**************

Public Function InsertImdAssign(ByVal xnav As String, ByVal xfreq As String, ByVal xsn As String, ByVal xfw As String, ByVal xdte As Date, ByVal xrecvd As String, ByVal xrels As String, ByVal xremarks As String, ByVal xcmpy As String, ByVal xrver As String, ByVal xplate As String, ByVal xdr As String, ByVal xassign As Date) As SqlDataReader
' Create Instance of Connection and Command Object
Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("connectionString"))
Dim MyCommand As SqlCommand
Dim strCommand As String

strCommand = "INSERT INTO tbl_Inbox ([imd_nav],[imd_freq],[imd_sn],[imd_fw],[imd_date],[imd_recvd],[imd_rels],[imd_remarks],[imd_cmpy],[imd_rver],[imd_plate],[imd_dr],[imd_drdte])"
strCommand = strCommand + "VALUES ('" & UCase(xnav) & "','" & UCase(xfreq) & "','" & xsn & "','" & xfw & "','" & xdte & "','" & xrecvd & "','" & xrels & "','" & xremarks & "','" & xcmpy & "','" & xrver & "','" & xplate & "','" & xdr & "','" & xassign & "')"
MyCommand = New SqlCommand(strCommand, myConnection)
' Execute the command
myConnection.Open()
Dim result As SqlDataReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection)

Return result
result.Close()
myConnection.Close()
End Function

What am I doing wrong?On what line do you get the error?
You never open conPubs.

Dim conPubs As New SqlConnection(ConfigurationSettings.AppSettings("connectionString"))
rs1 = New SqlClient.SqlDataAdapter("SELECT * FROM tbl_Inbox WHERE imd_sn = '" & TXTsn.Text & "'", conPubs)

conPubs.Open()

ds = New DataSet
rs1.Fill(ds, "imd_nav")
error occurred on this line:

Functions.InsertImdAssign(TXTnav.Text, TXTfreq.Text, TXTsn.Text, TXTfw.Text, TXTdate.Text, xrecvd, xrels, TXTremarks.Text, TXTcmpy.Text, TXTrver.Text, TXTplate.Text, TXTdr.Text, TXTassign.Text)
all,

still having this problem.. error occured at functions..

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.

kindly help
Set a breakpoint on this line (click the line, press F9 so a red dot appears beside the line, then press F5 to run the project):
Functions.InsertImdAssign(TXTnav.Text, TXTfreq.Text, TXTsn.Text, TXTfw.Text, TXTdate.Text, _
xrecvd, xrels, TXTremarks.Text, TXTcmpy.Text, TXTrver.Text, TXTplate.Text, TXTdr.Text, TXTassign.Text)
When this line is hit, and turns yellow, hover your mouse over each object - 'Functions', 'TXTfw' etc. One of these should give you an intellisense popup with a value of "nothing". If this is a textbox, make sure yuo've typed the name correctly, if this is another object like the "Functions" one, make sure it is instanciated and ready for use...
Don't you have to use 'Shared' if you want to call a function without instantiating first? I'm not sure, but give it a try.
Copy paste the entire error page for us please, so we can read the stack trace and the few lines of code it is highlighting.

Thanks.
A) It's ASP.Net, break points don't work the same way
B) I'm assuming the function is in the same class as the sub (or atleast an object is created somewhere for it). If it wasn't, they'd receive an error in design time and not be able to build it.
C) Your command is an INSERT, not a SELECT. A sqlDataReader won't be able to do anything with it. You need to use the ExecuteNonQuery member of MyCommand.
I don't see a class 'Functions'. Also, where do you create a new instance of it?
Copy paste the entire error page for us please, so we can read the stack trace and the few lines of code it is highlighting.

Thanks.

FUNCTIONS ERROR!!!

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
CMSnet.imd_outbox.cmdok_Click(Object sender, EventArgs e) in c:\inetpub\wwwroot\CMSnet\imd_outbox.aspx.vb:116
System.Web.UI.WebControls.Button.OnClick(EventArgs e)
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
System.Web.UI.Page.ProcessRequestMain() +1277

Object reference not set to an instance of an object.

When I run this code: tblMain.InnerHtml = "<tr><td>I'm sorry, you did not fill out one or more required "+
"fields (Title and or description). Please <a href=\"javascript:history.go(-1)\">go back</a> "+
"try again.</td></tr>";
tblMain is a HtmlTable which is defined as protected at the top and is set to runat server :confused: Any ideas? It's in C# in case you'd not noticed :)

ThanksOriginally posted by TomGibbons
tblMain is a HtmlTable which is defined as protected at the top ...

Thanks

But has it been instanciated? Defining is one thing, but it doesn't do much good until the instance is actualy created.

TG
I've never tried to do that as i'd say the majority of the time there will always be a better way of doing that sort of thing but anyway..... I just tried the same thing and get a different error message'HtmlTable' does not support the InnerHtml property. are you certain that this is the point where your code is failing?
Originally posted by Fishcake
I've never tried to do that as i'd say the majority of the time there will always be a better way of doing that sort of thing but anyway..... I just tried the same thing and get a different error message'HtmlTable' does not support the InnerHtml property. are you certain that this is the point where your code is failing? Ah, I wasn't getting that error message. Either way, I've gone about it a different way now and I'm getting the result I was after.

Thanks!

Object reference not set to an instance of an object.

I m getting this error "Object reference not set to an instance of an
object." when i run my application.

i m trying to select a value from dropdownlist

here is the code.

Protected Sub GetMsg(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles dgJobQueue.PreRender
ASPNET_MsgBox("welcome to msgbox")
dgJobQueue.FindControl("cboUserID")

Dim cboUserIdTemp As DropDownList =
CType(dgJobQueue.FindControl("cboUserID"), DropDownList)
Dim s As String = GetUserName()
Dim listItem As ListItem
cboUserIdTemp.SelectedValue = s
End SubAnd the line that throws the exception is?....

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Sometimes you eat the elephant.
Sometimes the elephant eats you.

<hina.pandya@.gmail.com> wrote in message
news:1117043143.865298.52560@.g49g2000cwa.googlegro ups.com...
>I m getting this error "Object reference not set to an instance of an
> object." when i run my application.
> i m trying to select a value from dropdownlist
> here is the code.
> Protected Sub GetMsg(ByVal sender As System.Object, ByVal e As
> System.EventArgs) Handles dgJobQueue.PreRender
> ASPNET_MsgBox("welcome to msgbox")
> dgJobQueue.FindControl("cboUserID")
> Dim cboUserIdTemp As DropDownList =
> CType(dgJobQueue.FindControl("cboUserID"), DropDownList)
> Dim s As String = GetUserName()
> Dim listItem As ListItem
> cboUserIdTemp.SelectedValue = s
> End Sub
cboUserIdTemp.SelectedValue = s
cboUserIdTemp.SelectedValue = s
cboUserIdTemp.SelectedValue = s
cboUserIdTemp.SelectedValue = s
Hi Hina

can you try this

if (cboUserIdTemp.Items.FindByText(s) != null) {
cboUserIdTemp.SelectedValue = s
}

This is C# code you can easily convert it to VB.NET

thanks

hina.pandya@.gmail.com wrote:
> cboUserIdTemp.SelectedValue = s
Nope, It not working .

I m trying to set selected value to dropdownlist which is inside
datagrid. and dropdownlist gets populated by other method.

Thanks
It looks like you didn't find the Control you were looking for. Are you sure
it's a child Control of the Control you're looking for it in? Are you sure
you spelled the ID correctly?

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Sometimes you eat the elephant.
Sometimes the elephant eats you.

<hina.pandya@.gmail.com> wrote in message
news:1117044323.952273.117990@.g44g2000cwa.googlegr oups.com...
> cboUserIdTemp.SelectedValue = s
This is the asp code that i have . ..now i m trying to set the selected
value as logged in user name .. i have user logged in id which returns
string. s now .. when ever i try to set cboUserIdTemp.SelectedValue =
s it gives me an error. ..

and if i try to do this

cboUserIdTemp.SelectedIndex =
cboUserIdTemp.Items.IndexOf(cboUserIdTemp.Items.Fi ndByValue(s)) it
gives me following error
Object reference not set to an instance of an object.
===============================================
Protected Sub GetMsg(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles dgJobQueue.PreRender
ASPNET_MsgBox("welcome to msgbox")
dgJobQueue.FindControl("cboUserID")

Dim cboUserIdTemp As DropDownList =
CType(dgJobQueue.FindControl("cboUserID"), DropDownList)
Dim s As String = GetUserName()
'Dim listItem As ListItem

'cboUserIdTemp.SelectedValue = s --> Error :Method not
found: Void
System.Web.UI.WebControls.ListControl.set_Selected Value(System.String).

cboUserIdTemp.SelectedIndex =
cboUserIdTemp.Items.IndexOf(cboUserIdTemp.Items.Fi ndByValue(s)) -->
Error: Object reference not set to an instance of an object.
'cboUserIdTemp.SelectedIndex = 1
End Sub

====================================

Protected Function PopulateProjectDropDownList()

Dim myCommand As SqlCommand = New SqlCommand("GetProjectList",
ripConn)
myCommand.CommandType = CommandType.StoredProcedure

ripConn.Open()
Return myCommand.ExecuteReader(CommandBehavior.CloseConne ction)

End Function

====================

<asp:TemplateColumn HeaderText="User Name">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" Width="15%"></ItemStyle>
<ItemTemplate>
<asp:Label id="Label2" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList id=cboUserID OnPreRender = '<%# GetMsg() %>'
tabIndex=1 runat="server" AutoPostBack="True" DataValueField="UserName"
DataTextField="UserName" DataSource="<%# PopulateUserNameDropDownList()
%>">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateColumn

Friday, March 16, 2012

Object reference not set to an instance of an object.

I have an asp.net app that I am trying to amend and have got stuck with the following error that comes up immediately I try to run it. Any suggestions about how I might identify the cause of the problem?
Clive Richardson
**************************************************
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.]
ConfigurationVB.WebForm1.Page_Load(Object sender, EventArgs e) +78
System.Web.UI.Control.OnLoad(EventArgs e) +67
System.Web.UI.Control.LoadRecursive() +35
System.Web.UI.Page.ProcessRequestMain() +744


We need to see the code that runs when the page loads.
Zath
Sorry... I found the problem. To do with a class that reads web.config.
Clive R

Object reference not set to an instance of an object.

Hi.

After finish a site on my own pc with VS2005 and i have run it with no problems i uploadet it to my host, i get this error:

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 156: ' Database Conn 2 Luk DBLine 157: Private Sub CloseDB2()Line 158: DBConnection2.Close()Line 159: DBConnection2 = NothingLine 160: DBAdapter2.Dispose()


Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.] DefaultVB.CloseDB2() in d:\web\localuser\mydomain.dk\public_html\Default.aspx.vb:158 DefaultVB.Page_Unload(Object sender, EventArgs e) in d:\web\localuser\mydomain.dk\public_html\Default.aspx.vb:66 System.Web.UI.Control.OnUnload(EventArgs e) +2067916 System.Web.UI.Control.UnloadRecursive(Boolean dispose) +267 System.Web.UI.Page.UnloadRecursive(Boolean dispose) +20 System.Web.UI.Page.ProcessRequestCleanup() +40 System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +154 System.Web.UI.Page.ProcessRequest() +86 System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +18 System.Web.UI.Page.ProcessRequest(HttpContext context) +49 ASP.default_aspx.ProcessRequest(HttpContext context) +29 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +154 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +64

My code_behind file is:

Imports SystemImports Telerik.QuickStartImports Telerik.WebControlsImports System.CollectionsImports System.ComponentModelImports System.DataImports System.DrawingImports System.WebImports System.Web.SessionStateImports System.Web.UIImports System.Web.UI.WebControlsImports System.Web.UI.HtmlControlsImports System.Data.OleDbImports System.ConfigurationImports Microsoft.VisualBasicPartialPublic Class DefaultVBInherits System.Web.UI.Page' Dim As s?tninger hvis skal bruges i flere Sub'sDim DBConnectionAs OleDbConnectionDim DBAdapterAs OleDbDataAdapterDim DBDataSetAs DataSetDim DBDataViewAs DataViewDim SQLStringAs String Dim DBConnection2As OleDbConnectionDim DBAdapter2As OleDbDataAdapterDim DBDataSet2As DataSetDim DBDataView2As DataViewDim SQLString2As String Dim DBConnection3As OleDbConnectionDim DBAdapter3As OleDbDataAdapterDim DBDataSet3As DataSetDim DBDataView3As DataViewDim SQLString3As String Dim DBConnection4As OleDbConnectionDim DBAdapter4As OleDbDataAdapterDim DBDataSet4As DataSetDim DBDataView4As DataViewDim SQLString4As String Dim DBConnection5As OleDbConnectionDim DBAdapter5As OleDbDataAdapterDim DBDataSet5As DataSetDim DBDataView5As DataViewDim SQLString5As String' K?rsel af diverse ting i Page_LoadSub Page_Load(ByVal senderAs Object,ByVal eAs EventArgs)Handles Me.LoadIf Request.QueryString("pageidentity") =Nothing OrElse Request.QueryString("pageidentity") =""Then Session("pageid") ="1"ElseIf Request.QueryString("pageidentity") <>""Then Session("pageid") = Request.QueryString("pageidentity").ToStringEnd If' Subs der skal k?res i Page_Load OpenDB1() OpenDB2() OpenDB3() OpenDB4() OpenDB5() LoadMenu()End Sub' K?rsel af diverse ting i Page_UnloadSub Page_Unload(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.Unload' Subs der skal k?res i Page_Unload CloseDB1() CloseDB2() CloseDB3() CloseDB4() CloseDB5()End Sub' Database Conn 1 ?ben DBPrivate Sub OpenDB1()' Connection til en database samt SQL Select forsp?rgsel DBConnection =New OleDbConnection(ConfigurationManager.ConnectionStrings("ConnectionStringDogs").ConnectionString) SQLString ="SELECT * FROM KennelEnggaardDogs WHERE OwnDog ='YES' ORDER BY DogID ASC;" DBAdapter = New OleDbDataAdapter(SQLString, DBConnection) DBDataSet = New DataSet() DBAdapter.Fill(DBDataSet, "KennelEnggaardDogs")' Hvis der ikke er data i databasen eller ingen recorder at vise, udskriv til en Label med id=NoRows If (DBDataSet.Tables(0).Rows.Count = 0) Then NoRows.Text = "<center><b>Vi har pt. ingen hunde selv.</b></center>" Else' Udskriv data til en Repeater med id=RepeaterShowOwnDogs DBDataView = New DataView(DBDataSet.Tables("KennelEnggaardDogs")) RepeaterShowOwnDogs.DataSource = DBDataView RepeaterShowOwnDogs.DataBind() End If End Sub' Database Conn 2 ?ben DB Private Sub OpenDB2()' Connection til en database samt SQL Select forsp?rgsel DBConnection2 = New OleDbConnection(ConfigurationManager.ConnectionStrings("ConnectionStringDogs").ConnectionString) SQLString2 = "SELECT * FROM KennelEnggaardDogs WHERE OwnDog ='YES' ORDER BY DogID ASC;" DBAdapter2 =New OleDbDataAdapter(SQLString2, DBConnection2) DBDataSet2 =New DataSet() DBAdapter2.Fill(DBDataSet2,"KennelEnggaardDogs")' Hvis der ikke er data i databasen eller ingen recorder at vise, udskriv til en Label med id=NoRows2If (DBDataSet2.Tables(0).Rows.Count = 0)Then NoRows2.Text ="<center><b>Vi har pt. ingen hunde til salg, men kontakt os endelig.</b></center>"Else' Udskriv data til en Repeater med id=RepeaterShowSalesDogs DBDataView2 =New DataView(DBDataSet2.Tables("KennelEnggaardDogs")) RepeaterShowSalesDogs.DataSource = DBDataView2 RepeaterShowSalesDogs.DataBind()End If End Sub' Database Conn 3 ?ben DBPrivate Sub OpenDB3()' Connection til en database samt SQL Select forsp?rgsel DBConnection3 =New OleDbConnection(ConfigurationManager.ConnectionStrings("ConnectionStringDogs").ConnectionString) SQLString3 ="SELECT * FROM KennelEnggaardText WHERE MainTextID =" & Session("pageid") &"" DBAdapter3 =New OleDbDataAdapter(SQLString3, DBConnection3) DBDataSet3 =New DataSet() DBAdapter3.Fill(DBDataSet3,"KennelEnggaardText")' Udskriv data til en FormView med id=FormViewMainText DBDataView3 =New DataView(DBDataSet3.Tables("KennelEnggaardText")) FormViewMainText.DataSource = DBDataView3 FormViewMainText.DataBind()End Sub' Database Conn 4 ?ben DBPrivate Sub OpenDB4()' Connection til en database samt SQL Select forsp?rgsel DBConnection4 =New OleDbConnection(ConfigurationManager.ConnectionStrings("ConnectionStringDogs").ConnectionString) SQLString4 ="SELECT * FROM KennelEnggaardText WHERE MainTextID = 2" DBAdapter4 =New OleDbDataAdapter(SQLString4, DBConnection4) DBDataSet4 =New DataSet() DBAdapter4.Fill(DBDataSet4,"KennelEnggaardText")' Udskriv data til en FormView med id=FormViewSubText DBDataView4 =New DataView(DBDataSet4.Tables("KennelEnggaardText")) FormViewSubText.DataSource = DBDataView4 FormViewSubText.DataBind()End Sub' Database Conn 5 ?ben DBPrivate Sub OpenDB5()' Connection til en database samt SQL Select forsp?rgsel DBConnection5 =New OleDbConnection(ConfigurationManager.ConnectionStrings("ConnectionStringDogs").ConnectionString) SQLString5 ="SELECT * FROM KennelEnggaardCont WHERE ContID = 1" DBAdapter5 =New OleDbDataAdapter(SQLString5, DBConnection5) DBDataSet5 =New DataSet() DBAdapter5.Fill(DBDataSet5,"KennelEnggaardCont")' Udskriv data til en FormView med id=FormViewCont DBDataView5 =New DataView(DBDataSet5.Tables("KennelEnggaardCont")) FormViewCont.DataSource = DBDataView5 FormViewCont.DataBind()End Sub' Database Conn 1 Luk DBPrivate Sub CloseDB1() DBConnection.Close() DBConnection =Nothing DBAdapter.Dispose() DBAdapter =Nothing End Sub' Database Conn 2 Luk DBPrivate Sub CloseDB2() DBConnection2.Close() DBConnection2 =Nothing DBAdapter2.Dispose() DBAdapter2 =Nothing End Sub' Database Conn 3 Luk DBPrivate Sub CloseDB3() DBConnection3.Close() DBConnection3 =Nothing DBAdapter3.Dispose() DBAdapter3 =Nothing End Sub' Database Conn 4 Luk DBPrivate Sub CloseDB4() DBConnection4.Close() DBConnection4 =Nothing DBAdapter4.Dispose() DBAdapter4 =Nothing End Sub' Database Conn 5 Luk DBPrivate Sub CloseDB5() DBConnection5.Close() DBConnection5 =Nothing DBAdapter5.Dispose() DBAdapter5 =Nothing End Sub' Behandling af MenuTabs 1/3Private Sub LoadMenu()Dim tabAs Tab = RadTabStrip1.FindTabByUrl(Request.Url.PathAndQuery)If Not (tabIs Nothing)Then tab.SelectParents()End If End Sub' Behandling af MenuTabs 2/3Protected Overrides Sub OnInit(ByVal eAs EventArgs) InitializeComponent()MyBase.OnInit(e)End Sub'OnInit ' Behandling af MenuTabs 3/3Private Sub InitializeComponent()End Sub'InitializeComponent ' Omregning af Hundens alder i ?r og Mdr. via datediff af dato nu og f?dtPublic Function GetAge(ByVal objAs Object)As String Dim bornAs DateTime = DateTime.ParseExact(obj.ToString(),"dd-MM-yyyy hh:mm:ss", System.Threading.Thread.CurrentThread.CurrentCulture)Dim ageAs TimeSpan = DateTime.Now.Subtract(born)Dim theRealAgeAs New DateTime(age.Ticks)Return (theRealAge.Year - 1) &" ?r " & (theRealAge.Month - 1) &" m?neder"End FunctionEnd Class

Hi.

So what do i have to do !? just remove the closeDB() !? or !?

and how do i use the Try...Finally code im my code !?


DBAdapter2.Fill(DBDataSet2,"KennelEnggaardDogs")
Hello,

Your problem is puzzling, but I believe theres an easy way to prevent it from happening, First issue is this line:

siraero:

Private Sub OpenDB2()' Connection til en database samt SQL Select forsp?rgsel DBConnection2 =New OleDbConnection(ConfigurationManager.ConnectionStrings("ConnectionStringDogs").ConnectionString)
Because your not explicitly calling DBConnection2.Open() , your DataAdapter on the following line is both opening the connection and closing it when you are done (seehttp://authors.aspalliance.com/aspxtreme/sys/data/Common/DataAdapterClassFill.aspx):

siraero:

DBAdapter2.Fill(DBDataSet2,"KennelEnggaardDogs")
 Therefore the way you are using this, there is no need for you to call your close methods on your Page.Unload event because your connections are already closed. For an even better way you should consider using Try..Finally block to ensure your connections are always closed.
 

before the unload event the data adapter will automatically close your connections, so to prevent this on load event insert your code inside the try catch finally blocks.

HC


Yes but how can i make my connection, maybe Sub OpenDB(), so it works with the Try-catch-finally and do i still just call em in the Page_Load as now but delete the CloseDB subs.

Im new in .net so hope u can help me.


I believe you dont have to call yourSub CloseDB1(),Sub CloseDB2(), etc on page_unload event, first because the data adapter will automatically open and close the connection to the databse so you dont need to handle it manually.Just to try it remove the code insideSub Page_Unload and try it,

HC


hi.

i just place a ' tage infront of the CloseDB#() and now it works.

do i then need the try cacht finally !?


It's better to put them in the try catch finally blocks in this case if an error occured during opening, retrieving data, and binding, you can handle it in the catch area.

try

{

OpenDB1()
OpenDB2()
OpenDB3()
OpenDB4()
OpenDB5()
LoadMenu()
}

catch(Exception ex)

{

Response.Write(ex.Message)

}

finally
{

CloseDB1()
CloseDB2()
CloseDB3()
CloseDB4()
CloseDB5()
}

HC

Object reference not set to an instance of an object.

Hi all,
I'm using a component in internet, which i put that .dll into my bin folder. after that I just follow the step to run the examples. However, the error come out.
Anyone can help me please?? thanks alot!!
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.] Bestcomy.Web.Controls.Upload.UploadModule.62aadb2cfa53b890() +51 Bestcomy.Web.Controls.Upload.UploadModule..ctor() +300[TargetInvocationException: Exception has been thrown by the target of an invocation.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly) +68 System.RuntimeType.CreateInstanceImpl(Boolean publicOnly) +175 System.Activator.CreateInstance(Type type, Boolean nonPublic) +61 System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +1091 System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +113 System.Web.Configuration.ModulesEntry.Create() +39 System.Web.Configuration.HttpModulesSection.CreateModules() +218 System.Web.HttpApplication.InitModules() +161 System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers) +1294 System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context) +424 System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context) +100 System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +191

Anyone can help?

Thank very much.


Can u post some of your code,
The error maybe becuase u didn use the NEW keyword to instansiate the components

As the error says a null value is getting assigned to an object! So please make sure data is there before assigning to the object!

I saw upload word in the stack, if you used for uploading (only guess), then make sure you really uploading before trying to grab value! Also make sure form attribute hasenctype="multipart/form-data"


hi, i using asp.net 2.0 so it will automatic compiled when load the page. i'm not loading the file in the default.aspx. why at the default page need to assign the upload object?

Object reference not set to an instance of an object.

Hi,
I've developed my first ASP.NET application using VS2005, when I run it from the IDE it works fine but after I deploy it under IIS, it no longer works.

It gives me this error

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.]
System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String name) +1841
System.Web.Hosting.ISAPIWorkerRequest.ReadRequestHeaders() +121
System.Web.Hosting.ISAPIWorkerRequest.GetKnownRequestHeader(Int32 index) +126
System.Web.Hosting.ISAPIWorkerRequestInProc.GetKnownRequestHeader(Int32 index) +104
System.Web.HttpWorkerRequest.HasEntityBody() +17
System.Web.HttpRequest.GetEncodingFromHeaders() +223
System.Web.HttpRequest.get_ContentEncoding() +48
System.Web.HttpRequest.get_QueryStringEncoding() +7
System.Web.HttpRequest.get_QueryStringText() +3379912
System.Web.HttpRequest.get_PathWithQueryString() +10
System.Web.Security.FormsAuthenticationModule.OnEnter(Object source, EventArgs eventArgs) +93
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +92
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +64



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

The code to the page that I call looks like:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Login : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
string fName = "";
string tCode = "";
string sBox = "";


fName = Request.QueryString[1];
tCode = Request.QueryString[0];
sBox = Request.QueryString[2];

string path = "xxxxxxx";

string link = "<a href=\"" + path + sBox + "/";

Session.Add("link", link);
Session.Add("tCode", tCode);

}

}

When I call the page I do pass the parameters in the url?

Thanx in advance

When things seem to work in the built in web server of VS2005 and not in IIS, the problem usually is security in my experience....


Seems like your applications is not configured as an IIS application. Try to create a virtual directory pointing the path of the project and access again~

Thanks
Is there anything(security related) specific I need to configure to make my application work under IIS?

Object reference not set to an instance of an object.

I m getting this error "Object reference not set to an instance of an
object." when i run my application.
i m trying to select a value from dropdownlist
here is the code.
Protected Sub GetMsg(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles dgJobQueue.PreRender
ASPNET_MsgBox("welcome to msgbox")
dgJobQueue.FindControl("cboUserID")
Dim cboUserIdTemp As DropDownList =
CType(dgJobQueue.FindControl("cboUserID"), DropDownList)
Dim s As String = GetUserName()
Dim listItem As ListItem
cboUserIdTemp.SelectedValue = s
End SubAnd the line that throws the exception is?....
HTH,
Kevin Spencer
Microsoft MVP
.Net Developer
Sometimes you eat the elephant.
Sometimes the elephant eats you.
<hina.pandya@.gmail.com> wrote in message
news:1117043143.865298.52560@.g49g2000cwa.googlegroups.com...
>I m getting this error "Object reference not set to an instance of an
> object." when i run my application.
> i m trying to select a value from dropdownlist
> here is the code.
> Protected Sub GetMsg(ByVal sender As System.Object, ByVal e As
> System.EventArgs) Handles dgJobQueue.PreRender
> ASPNET_MsgBox("welcome to msgbox")
> dgJobQueue.FindControl("cboUserID")
> Dim cboUserIdTemp As DropDownList =
> CType(dgJobQueue.FindControl("cboUserID"), DropDownList)
> Dim s As String = GetUserName()
> Dim listItem As ListItem
> cboUserIdTemp.SelectedValue = s
> End Sub
>
cboUserIdTemp.SelectedValue = s
cboUserIdTemp.SelectedValue = s
cboUserIdTemp.SelectedValue = s
cboUserIdTemp.SelectedValue = s
Hi Hina
can you try this
if (cboUserIdTemp.Items.FindByText(s) != null) {
cboUserIdTemp.SelectedValue = s
}
This is C# code you can easily convert it to VB.NET
thanks
hina.pandya@.gmail.com wrote:
> cboUserIdTemp.SelectedValue = s
Nope, It not working .
I m trying to set selected value to dropdownlist which is inside
datagrid. and dropdownlist gets populated by other method.
Thanks
It looks like you didn't find the Control you were looking for. Are you sure
it's a child Control of the Control you're looking for it in? Are you sure
you spelled the ID correctly?
HTH,
Kevin Spencer
Microsoft MVP
.Net Developer
Sometimes you eat the elephant.
Sometimes the elephant eats you.
<hina.pandya@.gmail.com> wrote in message
news:1117044323.952273.117990@.g44g2000cwa.googlegroups.com...
> cboUserIdTemp.SelectedValue = s
>
This is the asp code that i have . ..now i m trying to set the selected
value as logged in user name .. i have user logged in id which returns
string. s now .. when ever i try to set cboUserIdTemp.SelectedValue =
s it gives me an error. ..
and if i try to do this
cboUserIdTemp.SelectedIndex =
cboUserIdTemp.Items.IndexOf(cboUserIdTemp.Items.FindByValue(s)) it
gives me following error
Object reference not set to an instance of an object.
========================================
=======
Protected Sub GetMsg(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles dgJobQueue.PreRender
ASPNET_MsgBox("welcome to msgbox")
dgJobQueue.FindControl("cboUserID")
Dim cboUserIdTemp As DropDownList =
CType(dgJobQueue.FindControl("cboUserID"), DropDownList)
Dim s As String = GetUserName()
'Dim listItem As ListItem
'cboUserIdTemp.SelectedValue = s --> Error :Method not
found: Void
System.Web.UI.WebControls.ListControl.set_SelectedValue(System.String).
cboUserIdTemp.SelectedIndex =
cboUserIdTemp.Items.IndexOf(cboUserIdTemp.Items.FindByValue(s)) -->
Error: Object reference not set to an instance of an object.
'cboUserIdTemp.SelectedIndex = 1
End Sub
====================================
Protected Function PopulateProjectDropDownList()
Dim myCommand As SqlCommand = New SqlCommand("GetProjectList",
ripConn)
myCommand.CommandType = CommandType.StoredProcedure
ripConn.Open()
Return myCommand.ExecuteReader(CommandBehavior.CloseConnection)
End Function
====================
<asp:TemplateColumn HeaderText="User Name">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" Width="15%"></ItemStyle>
<ItemTemplate>
<asp:Label id="Label2" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList id=cboUserID OnPreRender = '<%# GetMsg() %>'
tabIndex=1 runat="server" AutoPostBack="True" DataValueField="UserName"
DataTextField="UserName" DataSource="<%# PopulateUserNameDropDownList()
%>">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateColumn>