473,725 Members | 2,251 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Whats the error:- System.NullRefe renceException:

What could cause the error:-
System.NullRefe renceException: Object reference not set to an instance of an
object.
Any ideas?
Nov 18 '05 #1
5 1593
Your code is attempting reference an object that is currently equal to Null
(or, Nothing if you are using VB).

-Chris
~
http://weblogs.austinspad.com/caustin

"Patrick.O. Ige" <Pa*********@di scussions.micro soft.com> wrote in message
news:EE******** *************** ***********@mic rosoft.com...
What could cause the error:-
System.NullRefe renceException: Object reference not set to an instance of
an
object.
Any ideas?

Nov 18 '05 #2
If you showed us some code, we'd probably be more likely to point out the
exact error..especial ly if you could provide a line #

Karl

--
MY ASP.Net tutorials
http://www.openmymind.net/
"Patrick.O. Ige" <Pa*********@di scussions.micro soft.com> wrote in message
news:EE******** *************** ***********@mic rosoft.com...
What could cause the error:-
System.NullRefe renceException: Object reference not set to an instance of an object.
Any ideas?

Nov 18 '05 #3
Well what i have is a Datagrid that ,Updates,Adds and Delete.
When i add i have no error but when i click Update and Delete commands it
fires an error..
The Error line is at :-

"ItemNumber = CType(Args.Item .FindControl("I temNumber"), TextBox).Text"

Any ideas?

My code is below(its my EditRecord Sub porgram):-
Sub EditRecord(ByVa l Src As Object, ByVal Args As DataGridCommand EventArgs)
Dim Command As String
Dim ItemNumber As String
Dim ItemType As String
Dim ItemSupplier As String
Dim ItemName As String
Dim ItemDescription As String
Dim ItemPrice As String
Dim ItemQuantity As String
Dim DBConnection As SqlConnection
Dim DBCommand As SqlCommand
Dim DBReader As SqlDataReader
Dim SQLString As String
Command = Args.CommandSou rce.Text

ItemNumber = CType(Args.Item .FindControl("I temNumber"), TextBox).Text
ItemType = CType(Args.Item .FindControl("I temType"),
DropDownList).S electedItem.Tex t
ItemSupplier = CType(Args.Item .FindControl("I temSupplier"),
TextBox).Text
ItemName = CType(Args.Item .FindControl("I temName"), TextBox).Text
ItemDescription = CType(Args.Item .FindControl("I temDescription" ),
TextBox).Text
ItemPrice = CType(Args.Item .FindControl("I temPrice"), TextBox).Text
ItemQuantity = CType(Args.Item .FindControl("I temQuantity"),
TextBox).Text

UpdateMessage.T ext = " "

Dim ValidRecord As Boolean = True

If Command = "Add" Or Command = "Update" Then

'-- CHECK FOR VALID RECORD ---

'-- Check for valid ItemNumber
If Len(ItemNumber) <> 6 Then
UpdateMessage.T ext &= "- Invalid Item Number length "
ValidRecord = False
ElseIf Not IsNumeric(Right (ItemNumber, 4)) Then
UpdateMessage.T ext &= "- Invalid Item Number format "
ValidRecord = False
Else
ItemNumber = UCase(ItemNumbe r)
End If

'-- Check for missing Item Supplier
If ItemSupplier = "" Then
UpdateMessage.T ext &= "- Missing Supplier "
ValidRecord = False
End If

'-- Check for missing Item Name
If ItemName = "" Then
UpdateMessage.T ext &= "- Missing Name "
ValidRecord = False
End If

'-- Check for missing Item Description
If ItemDescription = "" Then
UpdateMessage.T ext &= "- Missing Description "
ValidRecord = False
End If

'-- Check for valid Item Price
If Not IsNumeric(ItemP rice) Then
UpdateMessage.T ext &= "- Invalid Price format "
ValidRecord = False
End If

'-- Check for valid Item Quantity
If Not IsNumeric(ItemQ uantity) Then
UpdateMessage.T ext &= "- Invalid Quantity format "
ValidRecord = False
End If

If ValidRecord = True And Command = "Add" Then

'--- CHECK FOR DUPLICATE RECORD ---
DBConnection = New
SqlConnection(" server=(local); database=Northw ind;integrated security=true;" )
DBConnection.Op en()
SQLString = "SELECT Count(*) FROM products1 WHERE ItemNumber
= '" & ItemNumber & "'"
DBCommand = New SqlCommand(SQLS tring, DBConnection)
If DBCommand.Execu teScalar() <> 0 Then
UpdateMessage.T ext = "- Duplicate Item Number. Record
not added."
ValidRecord = False
End If
DBConnection.Cl ose()

End If

End If

If ValidRecord = True Then

Select Case Command

Case "Add"
SQLString = "INSERT INTO products1 " & _
"(ItemNumbe r, ItemType, ItemSupplier, ItemName, " & _
"ItemDescriptio n, ItemPrice, ItemQuantity) VALUES(" & _
"'" & ItemNumber & "', " & _
"'" & ItemType & "', " & _
"'" & Replace(ItemSup plier, "'", "''") & "', " & _
"'" & Replace(ItemNam e, "'", "''") & "', " & _
"'" & Replace(ItemDes cription, "'", "''") & "', " & _
ItemPrice & ", " & _
ItemQuantity & ")"
UpdateMessage.T ext = "- Record " & ItemNumber & " added"

Case "Update"
SQLString = "UPDATE products1 SET " & _
"ItemType = '" & ItemType & "', " & _
"ItemSuppli er = '" & Replace(ItemSup plier, "'", "''")
& "', " & _
"ItemName = '" & Replace(ItemNam e, "'", "''") & "', "
& _
"ItemDescriptio n = '" & Replace(ItemDes cription, "'",
"''") & "', " & _
"ItemPrice = " & ItemPrice & ", " & _
"ItemQuanti ty = " & ItemQuantity & " " & _
"WHERE ItemNumber = '" & ItemNumber & "'"
UpdateMessage.T ext = "- Record " & ItemNumber & " updated"

Case "Delete"
SQLString = "DELETE FROM products1 WHERE ItemNumber = '"
& ItemNumber & "'"
UpdateMessage.T ext = "- Record " & ItemNumber & " deleted"

End Select

DBConnection = New
SqlConnection(" server=(local); database=Northw ind;integrated security=true;" )
DBConnection.Op en()
DBCommand = New SqlCommand(SQLS tring, DBConnection)
DBCommand.Execu teNonQuery()
DBConnection.Cl ose()

If Command = "Add" Or Command = "Delete" Then

ViewState("Upda ted") = True
Page_Load(Me, EventArgs.Empty )
'Page_Load(ByRe f sender As System.Object, ByRef e As
System.EventArg s)
End If

End If

End Sub
"Karl Seguin" wrote:
If you showed us some code, we'd probably be more likely to point out the
exact error..especial ly if you could provide a line #

Karl

--
MY ASP.Net tutorials
http://www.openmymind.net/
"Patrick.O. Ige" <Pa*********@di scussions.micro soft.com> wrote in message
news:EE******** *************** ***********@mic rosoft.com...
What could cause the error:-
System.NullRefe renceException: Object reference not set to an instance of

an
object.
Any ideas?


Nov 18 '05 #4
Hello,

You het the error because Args.Item.FindC ontrol("ItemNum ber") does not find
the control and returns Nothing and/or the found control is not TextBox. You
cast the control to TextBox and if it is not a TextBox, it returns Nothing.
I assume that VB .NET works similarry than "control as TextBox" which
returns null, if the control is null or is not a TextBox. Then you try to
use its property.

It's basically the same if you do this:

Control control = null;
TextBox textBox = control as TextBox;
string text = textBox.Text; // exception happens in here

or this:

Label label = new Label();
TextBox textBox = label as TextBox;
string text = textBox.Text; // exception happens in here

JMu

"Patrick.O. Ige" <Pa*********@di scussions.micro soft.com> wrote in message
news:FA******** *************** ***********@mic rosoft.com...
Well what i have is a Datagrid that ,Updates,Adds and Delete.
When i add i have no error but when i click Update and Delete commands it
fires an error..
The Error line is at :-

"ItemNumber = CType(Args.Item .FindControl("I temNumber"), TextBox).Text"

Any ideas?

Nov 18 '05 #5
Thx Jarmo the reply.
But my html looks like the following below and ItemNumber is TEXTBOX!
I don't know why its returning Null then!
Its works with ASP.NET WebMatrix but gives the error with VStudio .Net!!!

<asp:DataGrid id="DataGridDis play" Width="560px" runat="server"
OnItemCommand=" EditRecord"
AutoGenerateCol umns="False"
BackColor="#F9F 9F9"
HeaderStyle-BackColor="#990 000"
HeaderStyle-ForeColor="#FFF FFF"
HeaderStyle-Font-Bold="True"
HeaderStyle-HorizontalAlign ="Center"
HeaderStyle-VerticalAlign=" Top"
ItemStyle-VerticalAlign=" Top"
ItemStyle-HorizontalAlign ="Center">

<Columns>

<asp:TemplateCo lumn>
<HeaderTemplate >
No<br>
<asp:TextBox id="ItemNumber " runat="server"/>
</HeaderTemplate>
<ItemTemplate >
<asp:TextBox id="ItemNumber " runat="server"
Text='<%# Container.DataI tem("ItemNumber ") %>'
ReadOnly="True"/>
</ItemTemplate>
</asp:TemplateCol umn>

<asp:TemplateCo lumn>
<HeaderTemplate >
Type<br>
<asp:DropDownLi st id="ItemType" runat="server"
DataSource='<%# ItemTypes %>'/>
</HeaderTemplate>
<ItemTemplate >
<asp:DropDownLi st id="ItemType" runat="server"
DataSource='<%# ItemTypes %>'
SelectedIndex=' <%# SetIndex(Contai ner.DataItem("I temType")) %>'/>
</ItemTemplate>
</asp:TemplateCol umn>

<asp:TemplateCo lumn>
<HeaderTemplate >
Supplier<br>
<asp:TextBox id="ItemSupplie r" runat="server"/>
</HeaderTemplate>
<ItemTemplate >
<asp:TextBox id="ItemSupplie r" runat="server"
Text='<%# Container.DataI tem("ItemSuppli er") %>'/>
</ItemTemplate>
</asp:TemplateCol umn>

<asp:TemplateCo lumn>
<HeaderTemplate >
Name<br>
<asp:TextBox id="ItemName" runat="server"/>
</HeaderTemplate>
<ItemTemplate >
<asp:TextBox id="ItemName" runat="server"
Text='<%# Container.DataI tem("ItemName") %>'/>
</ItemTemplate>
</asp:TemplateCol umn>

<asp:TemplateCo lumn>
<HeaderTemplate >
Description<br>
<asp:TextBox id="ItemDescrip tion" runat="server"
TextMode="Multi Line"
Cols="25"
Rows="2"/>
</HeaderTemplate>
<ItemTemplate >
<asp:TextBox id="ItemDescrip tion" runat="server"
Text='<%# Container.DataI tem("ItemDescri ption") %>'
TextMode="Multi Line"
Cols="25"
Rows="2"/>
</ItemTemplate>
</asp:TemplateCol umn>

<asp:TemplateCo lumn>
<HeaderTemplate >
Price<br>
<asp:TextBox id="ItemPrice" runat="server"
Text="0.00"/>
</HeaderTemplate>
<ItemTemplate >
<asp:TextBox id="ItemPrice" runat="server"
Text='<%# FormatNumber(Co ntainer.DataIte m("ItemPrice"), 2) %>'/>
</ItemTemplate>
</asp:TemplateCol umn>

<asp:TemplateCo lumn>
<HeaderTemplate >
Qty<br>
<asp:TextBox id="ItemQuantit y" runat="server"
Text="0"/>
</HeaderTemplate>
<ItemTemplate >
<asp:TextBox id="ItemQuantit y" runat="server"
Text='<%# Container.DataI tem("ItemQuanti ty") %>'/>
</ItemTemplate>
</asp:TemplateCol umn>

<asp:TemplateCo lumn>
<HeaderTemplate >
<br>
<asp:Button Text="Add" runat="server"/>
</HeaderTemplate>
<ItemTemplate >
<asp:Button Text="Update" runat="server"/>
</ItemTemplate>
</asp:TemplateCol umn>

<asp:TemplateCo lumn>
<HeaderTemplate >
<br>
</HeaderTemplate>
<ItemTemplate >
<asp:Button Text="Delete" runat="server"/>
</ItemTemplate>
</asp:TemplateCol umn>

</Columns>

</asp:DataGrid>
"Jarmo Muukka" wrote:
Hello,

You het the error because Args.Item.FindC ontrol("ItemNum ber") does not find
the control and returns Nothing and/or the found control is not TextBox. You
cast the control to TextBox and if it is not a TextBox, it returns Nothing.
I assume that VB .NET works similarry than "control as TextBox" which
returns null, if the control is null or is not a TextBox. Then you try to
use its property.

It's basically the same if you do this:

Control control = null;
TextBox textBox = control as TextBox;
string text = textBox.Text; // exception happens in here

or this:

Label label = new Label();
TextBox textBox = label as TextBox;
string text = textBox.Text; // exception happens in here

JMu

"Patrick.O. Ige" <Pa*********@di scussions.micro soft.com> wrote in message
news:FA******** *************** ***********@mic rosoft.com...
Well what i have is a Datagrid that ,Updates,Adds and Delete.
When i add i have no error but when i click Update and Delete commands it
fires an error..
The Error line is at :-

"ItemNumber = CType(Args.Item .FindControl("I temNumber"), TextBox).Text"

Any ideas?


Nov 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
3839
by: cricketunes | last post by:
Hi folks, this one's had me stumped! $conn=ora_logon("cricketunes@pickles","j8j3kf"); if ($conn != TRUE) die("Unable to connect to oracle, exiting...\n"); $cursor = ora_open($conn); if ($cursor != TRUE) die("Unable to open a cursor, exiting...\n");
5
2093
by: Mike M | last post by:
Hi all, I ahve the following SQL string but when i try to response.Write it there is a error where the ',' should be between "city" and "County" SQL = "INSERT * INTO customers (Company_Name, Category, Contact_Name, Contact_Title, Address_1, Address_2, City, County, Post_Code, Phone_1, Phone_2, Fax, Web_URL, email_Address, Delivery, Notes)" SQL = SQL & " VALUES('" & Request.Form("Company_Name") & "','" &
5
1983
by: Alexandre Martins | last post by:
Provider=Microsoft.Jet.OLEDB.4.0;UserId=Admin;Password=teste;Data Source=C:\Inetpub\wwwroot\inktoner\dados\db_inktoner.mdb;Persist Security Info=True I can't connect in my database ! whats wrong ?? tks
3
2041
by: mahsa | last post by:
Hi do you know whats wrong with this code? <asp:HyperLink id="HLink_Help" runat="server" NavigateUrl='<%# "javascript:window.open('comments.aspx?id=1,width=500,height=600, scrollBars=yes');" %>'>Need Help?</asp:HyperLink> -- mahsa
4
2768
by: sophie | last post by:
Whats going on here: Read in a number as a string: scanf("%s", &number); number = 12345, for arguements sake Print it like this its fine:
20
2460
by: Snis Pilbor | last post by:
Whats the point of making functions which take arguments of a form like "const char *x"? It appears that this has no effect on the function actually working and doing its job, ie, if the function doesn't write to x, then it doesnt seem like the compiler could care less whether I specify the const part. Quite the opposite, if one uses const liberally and then later goes back and changes the functions, headaches will inevitably occur as...
1
7546
by: Abubakar | last post by:
Hi, In my application, Some of my thread gets stuck somewhere. The vs2k5 debugging "Thread" window shows that stuck thread and I can I dentify it. In its Name column the following text is written: "std::_Container_base::_Orphan_all". What does this mean? Now some general info about whats happnening here: :this is a call to a SendMessage api, which I'm sending to my GUI window, and this call never makes it back. I have checked the GUI...
0
1296
by: cuddles | last post by:
hi im using IBM DB2 version 8 i have a procedure that should delete an error log table DELETE FROM TABLE1.ERR_MSG_LOG WHERE DATE(CRT_S) < (CURRENT DATE - 30 DAYS); but i keep getting this error: A database manager error occurred. CLI0604E CallableStatement get*** method was called without calling execute. SQLSTATE=S1010
7
3360
by: Rohit | last post by:
Hi, I am working on a switch module which after reading voltage through a port pin and caterogizing it into three ranges(open,low or high), passes this range to a function switch_status() with parameters value and signal ID. Signal Id is used to get a user configurable parameter inside a configuration file, which depends on the type of switch. I have implemented it as under. Please ignore those magic numbers as I have mimized logic to...
4
3940
by: (2b|!2b)==? | last post by:
template <typename T1, typename T2> struct MyDbInfo { MyDbInfo():m_pEnv(0), m_tran(0), m_db(0), m_idx(0) {} MyDbInfo(CDbEnv *env, DbTxn* tran, T1* db_ptr, T2 *idx_ptr):m_pEnv(env), m_tran(tran), m_db(db_ptr), m_idx(idx_ptr) {}
0
8889
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9116
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8099
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3228
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.