Using "New" for "Object reference not set to an instance of an object" error doesn't work...

Hi,

I'm trying to build a sql insert statement by reading through each textbox the footer of a DataGrid control. Here's my datagrid code:

<asp:DataGrid ID="Datagrid1" runat="server" OnPageIndexChanged="dgPersonnelType_PageChanger"
			AutoGenerateColumns="False" CellPadding="4" AlternatingItemStyle-BackColor="#FFFFBB"
			AllowPaging="True" PageSize="20" ShowFooter="True">
			<ItemStyle BackColor="WhiteSmoke" Font-Names="verdana" Font-Size="10px" />
			<Columns>
				<asp:TemplateColumn HeaderText="Insert">
					<HeaderStyle BackColor="#CCCC99" Font-Bold="true" Font-Names="verdana" Font-Size="12px" />
					<FooterTemplate>
						<asp:LinkButton ID="lbtnInsert" runat="server" CommandName="Insert">Insert</asp:LinkButton>
					</FooterTemplate>
				</asp:TemplateColumn>
				<asp:TemplateColumn HeaderText="Default Pay Rate">
					<HeaderStyle BackColor="#CCCC99" Font-Bold="true" Font-Names="verdana" Font-Size="12px" />
					<ItemTemplate>
						<asp:Label ID="Label1" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.DefaultPayRate", "{0:c}") %>'></asp:Label>
					</ItemTemplate>
					<EditItemTemplate>
						<asp:TextBox ID="TextBox1" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.DefaultPayRate", "{0:c}") %>'></asp:TextBox>
					</EditItemTemplate>
					<FooterTemplate>
						<asp:TextBox ID="txtDefaultPayRate" runat="server" Visible="true"></asp:TextBox>
					</FooterTemplate>
				</asp:TemplateColumn>
				<asp:TemplateColumn HeaderText="Default Piece Rate">
					<HeaderStyle BackColor="#CCCC99" Font-Bold="true" Font-Names="verdana" Font-Size="12px" />
					<ItemTemplate>
						<asp:Label ID="Label2" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.DefaultPieceRate") %>'></asp:Label>
					</ItemTemplate>
					<EditItemTemplate>
						<asp:TextBox ID="TextBox2" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.DefaultPieceRate") %>'></asp:TextBox>
					</EditItemTemplate>
					<FooterTemplate>
						<asp:TextBox ID="txtDefaultPieceRate" runat="server"></asp:TextBox>
					</FooterTemplate>
				</asp:TemplateColumn>
			</Columns>
			<FooterStyle BackColor="#FFFFBB" />
			<PagerStyle Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False"
				Font-Underline="False" HorizontalAlign="Center" BackColor="#CCCC99" Mode="NumericPages"
				VerticalAlign="Middle" />
			<AlternatingItemStyle BackColor="#FFFFBB" />
		</asp:DataGrid>

I omitted several columns to save space - they're just additional columns in the datagrid.

Here's the code behind that builds the insert statement (at least, it's supposed too...):

 

Private Sub dgPersonnelType_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles dgPersonnelType.ItemCommand

		If e.CommandName = "Insert" Then

			Dim txtDefaultPayRate As TextBox = Me.dgPersonnelType.FindControl("txtDefaultPayRate")
			Dim txtDefaultPieceRate As TextBox = Me.dgPersonnelType.FindControl("txtDefaultPieceRate")

			Dim sqlValues As String = ""

			dgSqlConn = New SqlConnection("DATACONNECTIONINFORMATION")
			Dim sqlCmd As SqlCommand
			Dim InsertCmd As String = "INSERT INTO rsrc_PersonnelType (LaborForceTypeID, DefaultPayRate, " & _
			   "DefaultPieceRate, DefaultAdminCostPercent, Rebill, Markup) VALUES (" & sqlValues & ")"""

			sqlCmd = New SqlCommand(InsertCmd, dgSqlConn)

			'Build INSERT statement by reading values in textboxes
			sqlValues &= IIf(sqlValues <> "", ",", "").ToString() & IIf(txtDefaultPayRate.Text <> "", txtDefaultPayRate.Text, "NULL").ToString()
			sqlValues &= IIf(sqlValues <> "", ",", "").ToString() & IIf(txtDefaultPieceRate.Text <> "", txtDefaultPieceRate.Text, "NULL").ToString()

			sqlCmd.Connection.Open()

			sqlCmd.ExecuteNonQuery()
			dgPersonnelTypeBindData()
			sqlCmd.Connection.Close()
		End If
	End Sub

 As you can see, I Dim the text boxes to be found in the datagrid control and then use "IIf" for each textbox to determine if there is a value in the text box, and if so, add it to the Insert statement.

But on run, clicking on the "Insert" button in the footer of the datagrid, the program errors on the first "sqlValues" line with the "Object reference not set to an instance of an object." error. Adding "New", as the error information box suggests justs generates blue "squigglies" under the textbox references in the sqlValues lines.

Any idea why I'm getting this and how to fix it?

Capella07


"f u cn rd ths, u cn gt a gd jb n cmptr prgmmng." - Anon
0
capella07
4/30/2007 2:40:45 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

8 Replies
1761 Views

Similar Articles

[PageSpeed] 16
Get it on Google Play
Get it on Apple App Store

Well, the thing I see is that you are trying to dynamically create a textbox with an ID that already exists.

If you can't access the textbox without the Dim .. as TextBox (have you tried?) then maybe just use a WithEvent to expose the textbox.

The reason for the "squiqly", I would imagine is that you are duplicating IDs... 


Andrew S. Erwin
Software Developer
ReflectSystems, Inc.

0
cyberwin
4/30/2007 2:50:31 PM

Hey, cyberwin. Thanks for replying.

I see what you're saying about "creating a textbox with an ID that already exists". No, I hadn't tried to access it without the Dim until you mentioned it. I tried working with that, but couldn't figure out exactly how to do it (you're talking with a real VB.NET noob here!). I'd appreciate it if you could "point me in the right direction" as far as doing that.

Thanks,

Capella07


"f u cn rd ths, u cn gt a gd jb n cmptr prgmmng." - Anon
0
capella07
4/30/2007 3:03:39 PM

By the way, here's what I tried:

			Dim defaultpayrateValue As String
			defaultpayrateValue = txtDefaultPayRate.FindControl("txtdefaultpayrate").ToString
 
"f u cn rd ths, u cn gt a gd jb n cmptr prgmmng." - Anon
0
capella07
4/30/2007 3:06:08 PM

When accessing the textbox, you should have direct control. Meaning, you don't need to use FindControl.

If you want to see the value of the textbox (what is in the textbox) just user

Dim x as String = txtDefaultPayRate.Text

If you cannot access it, you can place a protected withevent in your code behind and use the find control to expose it...

Andrew S. Erwin
Software Developer
ReflectSystems, Inc.

0
cyberwin
4/30/2007 3:17:24 PM

Ah, that's the deal, there. The textboxes are in a datagrid, so I do need to use FindControl (at least as I understand this, I need to).

So, according to what you said in your last post, I'd need to us a "protected withevent". How do I do that and have it work with the Sub I've got (below) that handles the Insert command?

Private Sub dgPersonnelType_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles dgPersonnelType.ItemCommand

Can that be nested within this sub for each textbox? How would that work?

Thanks!

Capella07


"f u cn rd ths, u cn gt a gd jb n cmptr prgmmng." - Anon
0
capella07
4/30/2007 3:28:01 PM

Well, first, try accessing the textbox directly.

A WithEvent should be placed inside your class, but outside of any sub or function...

An example would be...Imports System.Data.SqlClient

Imports System 

Partial Class documents
    Inherits System.Web.UI.Page

    Protected WithEvents (whatever the name of the textbox is) As TextBox

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

 

But I am pretty sure if you try to access the textbox directly it will work... 


Andrew S. Erwin
Software Developer
ReflectSystems, Inc.

0
cyberwin
4/30/2007 3:35:33 PM

Thanks, cyberwin

I'll work with that for a while and see what I can do.

Wish me luck!


"f u cn rd ths, u cn gt a gd jb n cmptr prgmmng." - Anon
0
capella07
4/30/2007 3:55:55 PM

dgSqlConn = New SqlConnection("DATACONNECTIONINFORMATION")

Should be DIM dgSqlConn as New SqlConnection(...)


Andrew S. Erwin
Software Developer
ReflectSystems, Inc.

0
cyberwin
5/24/2007 6:31:58 PM
Reply:

Similar Artilces:

Httpcontext.Current.Session["foo"]="foo" results in "Object reference not set to an instance of an object"
I tried to set a session variable in a App_Code class:  Httpcontext.Current.Session["foo"]="foo"; but I keep getting "Object reference not set to an instance of an object" error. How can I access Session object in a class file which is not part of a .aspx file? You are using c# right? System.Web.HttpContext.Current.Session["foo"] = "foo"; //for c#System.Web.HttpContext.Current.Session("foo") = "foo"; //for vb Your syntax is correct for setting a session variable inside a class file. Is session enabled for y...

"Error Creating Control"
 Hi everyone! I'm using VS 2005 and recently I added MSChart controls on it. Even I test the samples included on http://code.msdn.microsoft.com/mschart. My charts have to show data from a DB, so when I tried drop the chart control into the design view appears the error  message "Error Creating Control" - Object reference not set to an instance of an object instead of the chart control. I've been tried this on two differents PCs and happens the same. This happends when I drop the control, I still haven't compiled anything. But when I compile the web sit...

error creating control -"Object reference not set to an instance of object"
hi, I probably asking a old question asked before. But I am dyign here to have this question answered. We have a web user control and when we added it to the page, it always shows "Error creating cotrol" and when pointing to the the information icon. it says: Object reference not set to an instance of object. Please help me on this issue. Are you able to view the design surface of the control itself?...

Error using Crystal Report "Object referance not set to an instance of an object"
Hello, I am begginer using crystal Report in asp.net. I created one report in webform using crystal reportViewer. But there is error "System.NullReferanceException :  Object referance not set to an instance of an object." Please help me. I solved my problem using Sql Server user name and password. I think ,Without using password we cannot connect to sql database  for crystal report.(i.e. Using Windows Integrated Security) ...

"Object reference not set to an instance of an object" error in brand new project
Hi, New to the boards and having trouble debugging an error. I'm developing off Windows Server 2003 installed on a Virtual PC and program using ASP.net in Visual Studio 2005. Just yesterday, I began running into a "Object reference not set to an instance of an object" server error message whenever I try to run my existing web site. Setting breakpoints and debugging does no good as none of them are even hit. I tried created an entirely new ASP.NET web site and the same error pops up. Did a registry value get somehow corrupted on my VPC( I tend to use save state a lot)? I'm con...

Tab Control On Ajax Error
 hello guys, im newbie on this ajax word =), so im learning every day a litle bit more ... ajax is very cool, i saw all videos ajaxtoolkit  from ajaxcontrol toolkit web site and im learning with that cool stuff... it's ok my problem is when i try add a news tab panels ( off course inside tabcontainer), and i try see like it's looks in debug mode , i dont know what's the reason but my VS 2008 shows a error .it says : object reference not set to an instance of an object. im making the tabs in this way:   1 <cc1:TabContainer runat="server&...

error "Object reference not set to an instance of an object" when adding a new web form
hiya, i get the error "Object reference not set to an instance of an object" when adding a new web form to a web site this is what i am doing i launch vs 2005 beta 2 i create a new web site on the solutions explorer, i right click on the site and select "add new item" i select "web form" on the dialog box, and click "add" and that's when i get the error any ideas? f...

Error "Object reference not set to an instance of an object" when using Public Shared DataSet
Good afternoon,I am relatively new to asp.net and to website development in general. I have a question about a specific error message I am getting, but I would also welcome any broader feedback regarding my use of DataSets and shared variables. I am working on a vb.net page that would allow a user to: Upload an excel workbook and store the information from a sheet from the workbook in a DataTable in a DataSetDelete Unnecessary DataRows from the DataTableDelete Unnecessary DataColumns from the DataTable.Format the remaining info in the DataTableTransfer the information from the DataTable to a...

"Object reference not set to an instance of an object" error
I know users say this all the time - "I didn't change anything". In this case, it's true. I haven't modified DesktopDefault.aspx but it suddenly started crashing with a "Object reference not set to an instance of an object" error. The error is on the "<form runat="server">" line in the html. Many months ago, I put in some javascript to insure that the window was maximized at startup; I took that out with the same error result. What would cause the portal to crash on <form runat="server"> statement? here's the trace state...

Error "Object Reference not set to an instance of an Object"
Hi Guys I am having problem with my code. I dont know where I am doing mistake. It works perfectly on my system. But If I launch it on our development server I am getting error "Object Reference not set to an instance of an Object".(Line where I am getting this error is underlined). I tried in many different ways. But couldnt find a solution to this. Any help will be highly appreciated. here is my code , developed using asp.net1.1 + C#. Here AdFeatImage is a usercontrol which is used 10 times in this web page. @@@@@@@@@@@@@@@@@@@@@@@@  // AdFeatImage uc=new AdFeatImag...

"Object reference not set to an instance of an object. " error
Hi all, I wote the coding as below, and when I run it, it gave me "Object reference not set to an instance of an object. " error. Anyone know how tosolve it? Thanks a lot. ' connect to the DBDim conn As SqlConnection = New SqlConnection conn .ConnectionString = Cred.ConDB 'execute the stored proc StrExeSQL is the stringDim StrExeSQL As String = Cred.EXEgetCompName 'sqlcmd executes the string on the connection givenDim sqlCmd As SqlCommand sqlCmd = New SqlCommand(StrExeSQL, conn) ' add the parameters required by the sproc and stringWith sqlCmd .Parame...

Error "Object reference not set to an instance of an object"
Hi all, I have a problem consuming a web service. I create the THTTPRIO object of my service and then I try to call a method, but in this call I always catch the exception "Object reference not set to an instance of an object", for every method of the service. I use BDS2006 but I download an upgrade for wsdlImporter to correctly import WSDL that use schemaLocation with references to external XSD files. In this way I can correctly create the unit of the service. I try to test the web service with soapUI (and also with webservices studio) and with these applications methods neve...

"Object reference not set to an instance of an object" Error
Hi,I got this error on Sharepoint Server 2007. I can'y deploy my web part anyway. Firstly i was able to deploy but after that i started to get this error although i did not change anything? "Error 1 Object reference not set to an instance of an object. 0 0 "How can i solve this?  Regards..  You're not alone on this... looking for an answer too!  When do you actually get this error? Can you post a screen shot of it? ...oh, and do you have any custom workflows?   Steve I have the same problem too When do you actually get this error?when I have to ...

"Object reference not set to an instance of an object" error
everytime i create a new user, i get the following error and unable to see the frontpage of the time tracker. However, when i look up the database, the new user's id is already created. can anyone help? ============================================================ 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 ref...

Web resources about - Using "New" for "Object reference not set to an instance of an object" error doesn't work... - asp.net.presentation-controls

Resources last updated: 1/17/2016 8:03:12 AM