2014年7月13日 星期日

[RESOLVED] Object reference not set to an instance of an object.


Hi,

After having added the following assignment statement,


SqlCommand cmd = new SqlCommand("SELECT top 1 dpt_id,dpt_name,fld2,fld3,CONVERT(varchar,fld4,105) fld4,fld5,photo_fld6,fld12,fld131,fld132,CONVERT(varchar,fld10,22) as col_fld7, CONVERT(varchar,fld11,22) as col_fld9 FROM dpt where LTRIM(RTRIM(dpt_abbr))=@par_id and LTRIM(RTRIM(dpt_fld8))=@par_fld8", conn);

...
reader = cmd.ExecuteReader();

if (reader.HasRows)
//if (reader.Read())
{
reader.Read();
tb_dptname.Text = reader["dpt_name"].ToString();
tb_fld2.Text = reader["fld2"].ToString();
tb_fld3.Text = reader["fld3"].ToString();
tb_fld4.Text = reader["fld4"].ToString();
tb_fld5.Text = reader["fld5"].ToString();
tb_ph_fld6.Text = reader["photo_fld6"].ToString();
tb_fld7.Text = reader["col_fld7"].ToString();
...





I get this eror. why?


Server Error in '/App10' Application.

--------------------------------------------------------------------------------





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.]

   App10.Detail.Pfld5_Load(Object sender, EventArgs e) +1755

   System.Web.UI.Control.LoadRecursive() +70

   System.Web.UI.Pfld5.ProcessRequestMain(Boolean includeStfld5sBeforeAsyncPoint, Boolean includeStfld5sAfterAsyncPoint) +3177



 





--------------------------------------------------------------------------------

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18044  





what it is here?




wmec


App10.Detail.Pfld5_Load(Object sender, EventArgs e) +1755



Where you place the textboxes? If in another control use FindControl. You also check the textbox id typed correctly.

put a break point and check if tb_fld5.Text
is null or blank



Oned,

All the Textboxes shown above are available for being selected and I got no error when building the project, why do I need to to Findcontrol for them?





check if you are having control with the same id on another page.



Oned,

I've got the same error even if I use FindControl to declare the same set of TextBox again.



Gaurav,

Do you mean it is due to the same name of Textbox is being reused?





Here are some of possible reasons for this exception;



2 - cmd.Connection might not have instantiated like;


_SqlCommand.Connection = new SqlConnection("ConnectionString");

3-





I would consider placing a breakpoint in the code above to determine exactly where the error is occurring at.


However since it is a Null Reference Exception, you are attempting to access a property from a null object which can commonly occur using the
Object.ToString() method which could be happening in the code below : 


//You will need to ensure that your reader["key"] object is not null for each of these elements
tb_dptname.Text = reader["dpt_name"].ToString();
tb_fld2.Text = reader["fld2"].ToString();
tb_fld3.Text = reader["fld3"].ToString();
tb_fld4.Text = reader["fld4"].ToString();
tb_fld5.Text = reader["fld5"].ToString();
tb_ph_fld6.Text = reader["photo_fld6"].ToString();
tb_fld7.Text = reader["col_fld7"].ToString();

It's likely that one of the above columns being refereced from your reader doesn't exist, so when you attempt to use the ToString() method on one of these null objects you are recieving your error.


I would highly recommend using the breakpoint method to determine exactly where this is happening at (as it could be an issue as simple as a spelling error)




Thanks all. I also don't know why it is fine when I now directly run the project. But I've got the ssame error, once it (which is the same deployed project) is being called by one other project.



How to set a pause within the project, to debug the deployed project?


Right now, once I've enabled the following 2 lines in bold, the problem will come out. If I have disabled these 2 lines, then no problem.

                SqlCommand cmd = new SqlCommand("SELECT top 1 dpt_id,dpt_name,fld2,fld3,CONVERT(varchar,fld4,105) fld4,fld5,photo_fld6,fld12,fld131,fld132,CONVERT(varchar,fld10,22) as col_fld7, CONVERT(varchar,fld11,22) as col_fld9 FROM dpt where LTRIM(RTRIM(dpt_abbr))=@par_id
and LTRIM(RTRIM(dpt_fld8))=@par_fld8", conn);

                ...



                reader = cmd.ExecuteReader();



                if (reader.HasRows)

                {

                    reader.Read();

                    TextBox tb_dptnm = FindControl("tb_dptname") as TextBox;

                    tb_dptnm.Text = reader["dpt_name"].ToString();

                    ...

                    tot_rec++;

                }





Use Convert.ToString() instead of .toString(). it accepts even null values



You mentioned that the following lines were causing your null reference issue : 


TextBox tb_dptnm = FindControl("tb_dptname") as TextBox;
tb_dptnm.Text = reader["dpt_name"].ToString();

If that is the case, then the odds are that the FindControl() method is unable to actually access or find your tb_dptnm Textbox Control within your form and since it cannot find it, it is attempting to set the Text property of null (which will cause your error). This can easily be checked by placing a breakpoint in the code and checking what the value of your tb_dptnm variable is after that line is executed.


Another possiblility is that your reader["dpt_name"] value is null (in which case you are trying to use the ToString() method on it and will encounter the same problem.


I would recommend first - check both of these values being used and ensure that the names "tb_dptname" and "dpt_name" match the ID value of your TextBox and the column being returned in your DataReader respectively.


Secondly, you could simply add the necessary logic to check for nulls and basically ignore setting the value if it is null : 


//Checks if the TextBox is null
TextBox tb_dptnm = FindControl("tb_dptname") as TextBox;

//The Textbox was found - set it's Text property
if(tb_dptnm != null)
{
tb_dptnm.Text = reader["dpt_name"].ToString();
}

and 


//Now it also checks if your reader["dpt_name"] name is null
TextBox tb_dptnm = FindControl("tb_dptname") as TextBox;

//The Textbox was found - set it's Text property
if(tb_dptnm != null)
{
//Checks if your dpt_name value is not null
if(reader["dpt_name"] != null)
{
tb_dptnm.Text = reader["dpt_name"].ToString();
}
}

Alternatively, you can use the Convert.ToString() method which handles null values as well : 


TextBox tb_dptnm = FindControl("tb_dptname") as TextBox;

if(tb_dptnm != null)
{
tb_dptnm.Text = Convert.ToString(reader["dpt_name"]);
}









Hi,


Put the reader in a while loopand use convert to string.


SqlDataReader reader = command.ExecuteReader();

// Call Read before accessing data. 
while (reader.Read())
{
tb_fld5.Text = Convert.tostring(reader[""]);
}

// Call Close when done reading.
reader.Close();

if this not working can you please tell me at which line exception is throwing.



Thanks


Raj



Thanks a lot Rion.

Using "if" to check if "tb_dptnm" is null, is fine, but the relevant Textbox is really on the page like




        width="260px"
Font-Names="Times New Roman"
Font-Size="11pt"
runat="server" />


why is "tb_dptnm" null below, since the previous error disappears if I've put these?


//Checks if the TextBox is null
TextBox tb_dptnm = FindControl("tb_dptname") as TextBox;

//The Textbox was found - set it's Text property
if(tb_dptnm != null)
...







If that is how your TextBox appears, you should have no trouble accessing it through your code-behind simply by referring to its ID property :


//The "tb_dptnm" Textbox being referenced by its ID property and the Text being set
tb_dptnm.Text = "Example";

My initial thought was that it could have something to do with the mark-up being invalid (as some of the properties being used such as Font-Size and a few others are not proper properties) or by explicitly defining a closing tag instead of the self-closing one as seen below : 



If you are still encountering issues with accessing it through either the FindControl method or directly through its ID, I would recommend placing a breakpoint within the code and actually inspecting the element to see if it can be found.













Thanks a lot. I put it like


        width="260px"
Font-Names="Times New Roman"
Font-Size="11pt"
runat="server" >



by adding the closing tag. But once I've removed that "if" condition in the codebehind, then I've got the same problem. Why?





Any help?



I can't think of why you would be unable to reference the control (unless it was contained within some other container element or within a Master Page or something).


Try using the exact tag that I specified earlier : 


 ID="tb_dptname" Width="260" runat="server">

and then attempt to reference the element within your code-behind directly by its ID (instead of using the FindControl() method) : 


//Simply reference your TextBox by it's ID instead of using the FindControl() method
tb_dptnm.Text = Convert.ToString(reader["dpt_name"]);

If you are still encountering issues, you may want to consider posting your entire markup and code behind for the page in question and we can try and figure out exactly what could be causing this.





Thanks a lot Rion. Using these


//TextBox tb_dptnm = FindControl("tb_dptname") as TextBox;
//if (tb_dptnm != null)
//{
//tb_dptnm.Text = reader["dpt_name"].ToString();
//}
tb_dptname.Text = Convert.ToString(reader["dpt_name"]);
...



with exactly this Textbox on the page


            width="260px"
runat="server" >





I'm still getting the same problem.





Server Error in '/App10' Application.

--------------------------------------------------------------------------------





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.]

   App10.Detail.Page_Load(Object sender, EventArgs e) +1558

   System.Web.UI.Control.LoadRecursive() +70

   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3177



 





--------------------------------------------------------------------------------

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18044 



I can't see anything wrong with the code that you are using and it should be working just fine.


Have you tried placing a breakpoint and checked some of the values within your code to attempt to figure out exactly where your tb_dptname TextBox is located? The only thing that I can think of is that it is possibly located within another container element
(which you might have to use to reference it from) or within another Row, Master Page, etc.


You mentioned that your other values are working but the tb_dptname one is not. Could you post some additional code where the other TextBoxes are defined as well (any additional code would actually be helpful) so that we can try and figure out exactly
what is going wrong here.



Sorry, if I directly debug it in VS2012, I have got no problem.



When it (that is the deployed) is being called by one other project, and it is only having these assignment statements for these 2 Textboxes, then I am still having the error.


if (reader["dpt_name"] != null)
{
tb_dptname.Text = Convert.ToString(reader["dpt_name"]);
}
if (reader["fld2"] != null)
{
tb_fld2.Text = Convert.ToString(reader["fld2"]);
}
if (reader["fld3"] != null)
{
tb_fld3.Text = Convert.ToString(reader["fld3"]);
}





try like this


if (reader["dpt_name"] != null)
{
if (reader["dpt_name"] != DBNull.Value)
{
...
}
}







Sorry, with only one assignment line for the Textbox, like


if (reader["dpt_name"] != null)
{
if (reader["dpt_name"] != DBNull.Value)
{
tb_dptname.Text = Convert.ToString(reader["dpt_name"]);
}
}



                   

I'm still having the same error.



And just for clarification, this code is actually appearing in the same page (Web Form) that your TextBox control is declared in correct?


As I noticed that you had mentioned it was being called from another Project, I just wanted to ensure that you weren't trying to access a TextBox that didn't appear on the actual Web Form itself.



Yes, the current project is App10 and the code above is in Page_Load of this project.



But the error is mentioning 'App10' even if 'App10' has been called by App9 project. The error means the current project is App10 right?





Please check your asp page, and the code behind again.


I believe you show different IDs, although I can't see them while I am typing this reply.


One has a "name" suffix, while the other has a "nme" suffix.


My mistake. The ID values are the same.


I cannot retract this post. sorry.


 



Any help please?



Can you tell me what you see when you run the stored procedure from SSMS?


Just curious if any rows are selected, and if any of the rows selected have NULL values.



In SSMS, I see the relevant record with the same value of given parameters, is existing in the table.



Hello,


May I suggest that you change the textbox control name you have?


TextBox tb_dptnm =
FindControl("tb_dptname")
as TextBox;


Try something like tb_dptname_Testing.


Make the change on one single ASP page, and then change the above FindControl, to locate the new TextBox.


Also, after the FindControl, check the return code to ensure that it executed successfully.


By changing the name to something relatively unique, you can ensure that the TextBox ID was not used on more than one single ASP page, and then by checkiing the return code, you will know that the FindControl actually executed successfully.


 


Hope this helps.


沒有留言:

張貼留言