473,714 Members | 2,475 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

System.NullRefe renceException: Object reference not set to an inst

I'm loading an Array below but getting the error "Object reference not set to
an instance saying 'ItemNumber = CType(Args.Item .FindControl("I temNumber"),
TextBox).Text' is the error line.
I DON'T KNOW WHAT I'M DOING WRONG I USED ASP.NETWebMatri x and its working
well!!
Any help!!
I have declared ItemNumber as u can see below
" :-

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
' Load array ItemNumberList with item numbers
'Dim ItemNumberList = New ArrayList
Dim ItemNumberList = New ArrayList
DBConnection = New
SqlConnection(" server=(local); database=Northw ind;integrated security=true;" )
DBConnection.Op en()
SQLString = "SELECT ItemNumber FROM products1 ORDER BY ItemNumber"
DBCommand = New SqlCommand(SQLS tring, DBConnection)
DBReader = DBCommand.Execu teReader()
While DBReader.Read()
ItemNumberList. Add(DBReader("I temNumber"))
End While
DBReader.Close( )
DBConnection.Cl ose()
ItemNumberList. TrimToSize()
End Sub

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

Nov 18 '05 #1
3 4148
Hi,

The code in Page_Load() has nothing to do with these two lines:

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

What is Args? It looks like you already know the control name. Why not?:

ItemNumber = ItemNumber.Text

That should work fine. Are the two lines of code above in another
subroutine? The code you posted doesn't seem relevant in any way to each
other. Please post a better sample of what you are trying to do. Thanks
and 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.

"Patrick.O. Ige" <Pa*********@di scussions.micro soft.com> wrote in message
news:F8******** *************** ***********@mic rosoft.com...
I'm loading an Array below but getting the error "Object reference not set to an instance saying 'ItemNumber = CType(Args.Item .FindControl("I temNumber"), TextBox).Text' is the error line.
I DON'T KNOW WHAT I'M DOING WRONG I USED ASP.NETWebMatri x and its working
well!!
Any help!!
I have declared ItemNumber as u can see below
" :-

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
' Load array ItemNumberList with item numbers
'Dim ItemNumberList = New ArrayList
Dim ItemNumberList = New ArrayList
DBConnection = New
SqlConnection(" server=(local); database=Northw ind;integrated security=true;" ) DBConnection.Op en()
SQLString = "SELECT ItemNumber FROM products1 ORDER BY ItemNumber"
DBCommand = New SqlCommand(SQLS tring, DBConnection)
DBReader = DBCommand.Execu teReader()
While DBReader.Read()
ItemNumberList. Add(DBReader("I temNumber"))
End While
DBReader.Close( )
DBConnection.Cl ose()
ItemNumberList. TrimToSize()
End Sub

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

Nov 18 '05 #2
Hi Ken and thanks for the reply! (My Code below!!!)
What i'm trying to do is a datagrid that has Add,Update,Dele te commands.My
Add command is working but my Delete and Update command is giving error :-
System.NullRefe renceException: Object reference not set to an instance of an
object.
Refering to the line code:- ItemNumber =
CType(Args.Item .FindControl("I temNumber"), TextBox).Text
Don't know whats wrong IT WORKS WITH ASP.NETWEBMATRI X!!
But VS.Net give such errors!
Any help Thanks!!

'Option Explicit On
Imports System.Data
Imports System.Data.Sql Client
Imports System.Web.UI.W ebControls

Public Class datagrid_edit_d elete
Inherits System.Web.UI.P age

'Dim ItemTypes As New ArrayList
Protected ItemTypes As New ArrayList
'Protected WithEvents ItemType As System.Web.UI.W ebControls.Drop DownList
Protected WithEvents Button As System.Web.UI.W ebControls.Butt on
Protected WithEvents PageButtons As System.Web.UI.W ebControls.Plac eHolder
Protected WithEvents UpdateMessage As System.Web.UI.W ebControls.Labe l
Protected WithEvents DataGridDisplay As System.Web.UI.W ebControls.Data Grid
Protected WithEvents TextBox1 As System.Web.UI.W ebControls.Text Box
'Dim ItemNumberList As New ArrayList

'Protected WithEvents ItemTypes As System.Web.UI.W ebControls.Drop DownList


#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
<System.Diagnos tics.DebuggerSt epThrough()> Private Sub
InitializeCompo nent()

End Sub

'NOTE: The following placeholder declaration is required by the Web Form
Designer.
'Do not delete or move it.
Private designerPlaceho lderDeclaration As System.Object

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeCompo nent()
End Sub

#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
'Put user code to initialize the page here

Dim DBConnection As SqlConnection
Dim DBCommand As SqlCommand
Dim DBReader As SqlDataReader
Dim SQLString As String
Dim PageSize As Integer = 6

'-- Load array ItemNumberList with item numbers
'Dim ItemNumberList = New ArrayList
Dim ItemNumberList = New ArrayList
DBConnection = New
SqlConnection(" server=(local); database=Northw ind;integrated security=true;" )
DBConnection.Op en()
SQLString = "SELECT ItemNumber FROM products1 ORDER BY ItemNumber"
DBCommand = New SqlCommand(SQLS tring, DBConnection)
DBReader = DBCommand.Execu teReader()
While DBReader.Read()
ItemNumberList. Add(DBReader("I temNumber"))
End While
DBReader.Close( )
DBConnection.Cl ose()
ItemNumberList. TrimToSize()

'-- Create Paging Buttons
Dim StartIndex = 0
Dim EndIndex As Integer
Dim StartKey As String
Dim EndKey As String
Dim i As Integer

PageButtons.Con trols.Clear()
For i = 1 To Math.Ceiling(It emNumberList.Co unt / PageSize)

EndIndex = StartIndex + PageSize - 1
If EndIndex > ItemNumberList. Count - 1 Then
EndIndex = ItemNumberList. Count - 1
End If

StartKey = ItemNumberList( StartIndex)
EndKey = ItemNumberList( EndIndex)

Dim PageButton As Button
PageButton = New Button
PageButton.Text = i
PageButton.ID = "P" & i
PageButton.Comm andName = StartKey & "|" & EndKey
PageButton.Styl e("width") = "20px"
PageButton.Styl e("background-color") = "#F0F0F0"
AddHandler PageButton.Comm and, AddressOf GetPage
PageButtons.Con trols.Add(PageB utton)

StartIndex += PageSize

Next

'== CREATE ARRAYLIST FOR BINDING ITEM TYPES

ItemTypes = New ArrayList
DBConnection = New
SqlConnection(" server=(local); database=Northw ind;integrated security=true;" )
DBConnection.Op en()
SQLString = "SELECT DISTINCT ItemType FROM products1 ORDER BY
ItemType"
DBCommand = New SqlCommand(SQLS tring, DBConnection)
DBReader = DBCommand.Execu teReader()
While DBReader.Read()
ItemTypes.Add(D BReader("ItemTy pe"))
End While
DBReader.Close( )
DBConnection.Cl ose()

If Not Page.IsPostBack Or ViewState("Upda ted") = True Then

DBConnection = New
SqlConnection(" server=(local); database=Northw ind;integrated security=true;" )
DBConnection.Op en()
SQLString = "SELECT TOP " & PageSize & " * FROM products1 ORDER
BY ItemNumber"
DBCommand = New SqlCommand(SQLS tring, DBConnection)
DBReader = DBCommand.Execu teReader()
DataGridDisplay .DataSource = DBReader
DataGridDisplay .DataBind()
DBReader.Close( )
DBConnection.Cl ose()

Dim FirstButton As Button
FirstButton = CType(PageButto ns.FindControl( "P1"), Button)
FirstButton.Sty le("background-color") = "#990000"
FirstButton.Sty le("color") = "#FFFFFF"

ViewState("Upda ted") = False

End If

End Sub

Sub GetPage(ByVal Src As Object, ByVal Args As CommandEventArg s)

Dim DBConnection As SqlConnection
Dim DBCommand As SqlCommand
Dim DBReader As SqlDataReader
Dim SQLString As String

Dim Keys() As String
Keys = Split(Args.Comm andName, "|")

DBConnection = New
SqlConnection(" server=(local); database=Northw ind;integrated security=true;" )
DBConnection.Op en()
SQLString = "SELECT * FROM products1 WHERE " & _
"ItemNumber >= '" & Keys(0) & "' AND " & _
"ItemNumber <= '" & Keys(1) & "' " & _
"ORDER BY ItemNumber"
DBCommand = New SqlCommand(SQLS tring, DBConnection)
DBReader = DBCommand.Execu teReader()
DataGridDisplay .DataSource = DBReader
DataGridDisplay .DataBind()
DBReader.Close( )
DBConnection.Cl ose()

'-- Highlight clicked button
Dim Item As Button
Dim ThisButton As Button
For Each Item In PageButtons.Con trols
ThisButton = CType(Item, Button)
ThisButton.Styl e("background-color") = "#F0F0F0"
ThisButton.Styl e("color") = "#000000"
Next
ThisButton = CType(PageButto ns.FindControl( Src.id), Button)
ThisButton.Styl e("background-color") = "#990000"
ThisButton.Styl e("color") = "#FFFFFF"

End Sub
Function SetIndex(ByVal TheItem As String)
Dim i As Integer
For i = 0 To ItemTypes.Count - 1
If TheItem = ItemTypes(i) Then
Return i
End If
Next
End Function

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

End Class

Nov 18 '05 #3
Hi,

The datagrid.... The datagrid isn't my thing. I used it a couple times,
got frustrated, and wrote my own. Hopefully someone in the group can point
you in the right direction. I looked through the help file that comes with
VS.Net, in VS.Net they reference .controls(0) to CType() the control:

Sub MyDataGrid_Upda te(sender As Object, e As DataGridCommand EventArgs)
' For bound columns the edited value is stored in a Textbox.
' The TextBox is the 0th element in the column's cell.
Dim qtyText As TextBox = CType(e.Item.Ce lls(2).Controls (0), TextBox)
Dim priceText As TextBox = CType(e.Item.Ce lls(3).Controls (0),
TextBox)

Dim item As String = e.Item.Cells(1) .Text
Dim qty As String = qtyText.Text
Dim price As String = priceText.Text

Here is the link to the full source:
"ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemWebU IWebControlsDat aGridC
ommandEventArgs ClassTopic.htm"

Open up the help and paste that in the address bar.

I would try that. I don't know why WebMatrix would work and VS.Net
wouldn't. 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.
Nov 18 '05 #4

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

Similar topics

3
9139
by: Terrence | last post by:
I am doing some of the C# walkthroughs to transition from VB to C#. When I try to execute static void Main() { Aplication.Run(new Form1()) } I raise a 'System.NullReferenceException" in system.windows.forms.dll
0
1186
by: Hemil | last post by:
Hello Friends, I need your help in resolving the above error message in my asp.net application. Surprisingly, when I build and run the solution on my local machine it works fine but I get the error on the server box on which the application is hosted. I have checked that the .NET framework versions are same (1.1) on both my machine and the server. I remember seeing this application working on the server sometime back. But when I...
3
1702
by: mikeorb | last post by:
Is there a way to determine the object that a property is in? For example: function MyClass() { ... } MyClass.prototype.myFunc = function() { ... } var obj = new MyClass(); var sameobj = SOMEFUNCTION(obj.myFunc); So my goal is to get a reference to the object by just having the
7
8101
by: mike p. | last post by:
I have a docbook xml file, and am using standard docbook 1.61.3 xsl stylesheets to do xhtml transform. Transform works fine when using MSXML. When I try to do the following using asp.net 1.1: private void Page_Load(object sender, System.EventArgs e) { // load content XslTransform trans = new XslTransform();
0
9776
by: muralidharan | last post by:
WebForm1.aspx Code: <%@ Register TagPrefix="ComponentArt" Namespace="ComponentArt.Web.UI" Assembly="ComponentArt.Web.UI" %> <ComponentArt:TreeView id="TreeView1" Height="520" AutoPostBackOnNodeMove="false" DragAndDropEnabled="true" NodeEditingEnabled="False" KeyboardEnabled="true" CssClass="TreeView" NodeCssClass="TreeNode" SelectedNodeCssClass="SelectedTreeNode" HoverNodeCssClass="HoverTreeNode" NodeEditCssClass="NodeEdit"
2
7834
by: Raed Sawalha | last post by:
i have a windows form(Main) with listview, when click an item in listview i open other window form (Sub) which generate the selected item from parent window in as treeview items when click any item in treeview i display the content item in axWebBrowser, i close the sub form normally when i close the main the following error is generated An unhandled exception of type 'System.NullReferenceException' occurred in system.windows.forms.dll ...
1
4089
by: msnews.microsoft.com | last post by:
I'm trying to fill an array of objects but when I add the first object I get a NullReferenceException. ---------------------------------------------------------------------------- ------------------------------------------- Public Class TestClass Public NextSubIndex As Integer = 1 Public arrTestSubClass() As TestSubClass
2
2779
by: sxiao | last post by:
Hi, there I got a NullReferenceException when there are more than one users trying to open the same page at the same time. The senerio is: Two users logged into the web application using the Windows domain user account and tried to open the same page which has the databasde query code. When the two user tried to open the same page at the same time, there is a runtime error messsage showing as follows:
6
22216
by: William Mild | last post by:
I must be getting brain fried. I can't see the error. Create a new web form with the following code begind: Public Class test Inherits System.Web.UI.Page Public Class ReportCardData Public Structure Attend Dim DaysTardy As Double
2
1160
by: itsvineeth209 | last post by:
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 236: GridViewRow row = GridView1.Rows; Line 237:
0
8796
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
8704
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
9170
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9009
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
7946
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...
1
6627
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4462
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3155
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
3
2105
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.