c# - visual studio 中的 nullreferenceexception

标签 c# nullreferenceexception

<分区>

我的代码中出现 NullReferenceException。

我从同一项目中的另一个页面调用方法 datecheck 并将两个字符串作为参数传递。这些包含用户以字符串格式选择的日期。 现在,当我尝试使用这些字符串值初始化 2 个标签 label1 和 label2 时,我得到了 NullReferenceException。

显示错误和堆栈跟踪的代码行如下:

Line 39:         public void datecheck(String s1, String s2)
Line 40:         {
Line 41:             Label1.Text = s1;
Line 42:             Label2.Text = s2;            
Line 43:         }

源文件:I:\Aditya\GuestHouse\GuestHouseApp\GuestHouseApp\Booking Status.aspx.cs 行:41

堆栈跟踪:

[NullReferenceException: Object reference not set to an instance of an object.]
GuestHouseApp.Booking_Status.datecheck(String s1, String s2) in I:\Aditya\GuestHouse\GuestHouseApp\GuestHouseApp\Booking Status.aspx.cs:41
GuestHouseApp.Booking.Button1_Click(Object sender, EventArgs e) in I:\Aditya\GuestHouse\GuestHouseApp\GuestHouseApp\Booking.aspx.cs:28
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +113
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5348

最佳答案

注意错误信息和行号。以下是读取堆栈跟踪的方法:

对象引用[为空且]未设置为对象实例[在方法] GuestHouseApp.Booking_Status.datecheck [at file:line] Status.aspx.cs:41

如果编译后的代码是最新的,那么这意味着行 Label1.Text = s1; 是引发异常的行。

此外,可以推断 Label1 为空,因为发生这种情况时会引发 NullReferenceException:(anExpressionEvaluatingToNull).Member。在该行中访问的显式接收器(可能为空)的唯一成员是Text,因此Label1 必须为空。

如果需要,使用调试器:然后您可以检查当前的变量和对象。

快乐编码。

关于c# - visual studio 中的 nullreferenceexception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6555318/

相关文章:

c# - Null Dapper.net 查询仍然使用 FirstOrDefault() 返回 Null Reference Exception

c# - 堆栈跟踪如何指向错误的行( “return”语句)-关闭40行

c# - 将目标框架从 v4.0 更改为 v3.5 后找不到命名空间

c# - LINQ 查询中的 NullReferenceException

c# - 导航管理器 NullReferenceException

c# - 为什么我的图片框即使显示图像也是空的?

c# - 从 DataAdapter 填充 DataTable - 选择了错误的列作为主键

c# - 该类型必须是引用类型才能将其用作泛型类型或方法中的参数 'T'

c# - 无法将控件添加到用户控件

c# - 使用 PostSharp 将属性应用于界面