C# System.NullReferenceException 从 class 中的方法返回值时
C# System.NullReferenceException while returning value from Method in class
我在名为 clsFoldingManagement
的 class 中创建了方法名称 fetchProjectsForUpdateQty
。在通过函数(以数据集的形式)返回值数据时,我在 winform 组合框中收到错误消息,指出对象引用未设置为对象实例。下面是我在 class clsFoldingManagement
中编写的方法 fetchProjectsForUpdateQty
代码
public static DataSet fetchProjectsForUpdateQty(int client_id)
{
using (var con = new SqlConnection(ConStr))
{
string query = "select tblClient.ProjectName, tblFolding.Name , tblFolding.FoldingID from tblStockManagement LEFT OUTER JOIN tblClient ON tblClient.Client_ID=tblStockManagement.Client_ID LEFT OUTER JOIN tblFolding ON tblFolding.FoldingID=tblStockManagement.Client_ID where tblStockManagement.client_id=@clientid and tblStockManagement.quantity >0";
using (var cmd = new SqlCommand(query, con))
{
con.Open();
cmd.Parameters.Add("@clientid", SqlDbType.Int).Value = client_id;
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, con);
DataSet ds = new DataSet();
da.Fill(ds, "DATA");
return ds;
}
}
}
并且我在我的组合框点击事件中编写了以下代码 (cbUpdateProject_Click
)
cbUpdateItemName.DataSource = null;
//DataSet data = clsFoldingManagement.fetchProjectDetails();
DataSet ds = clsFoldingManagement.fetchProjectsForUpdateQty(int.Parse(cbUpdateProject.SelectedValue.ToString()));
cbUpdateProject.DataSource = ds.Tables["DATA"].DefaultView;
cbUpdateProject.DisplayMember = "ProjectName";
cbUpdateProject.ValueMember= "Client_ID";
这是我得到的异常详细信息:
System.NullReferenceException was unhandled
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=FazalConstructions
StackTrace:
at FazalConstructions.frmStockMoving.cbUpdateProject_Click(Object sender, EventArgs e) in e:\Waqas Folder\FazalConstruction\FazalConstructions\FazalConstructions\frmStockMoving.cs:line 87
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.ComboBox.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at FazalConstructions.Program.Main() in e:\Waqas Folder\FazalConstruction\FazalConstructions\FazalConstructions\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
object reference is not set to an instance of object
是我最喜欢抛出的错误之一,它的意思正是它所说的。您在代码中引用的对象未设置为对象的实例。
首先,最好确定哪一行代码引发了异常。
然后分析行中的对象并确保它们不为空。如果您说 cbUpdateProject.DataSource = ds.Tables["DATA"].DefaultView;
并且 ds.Tables["DATA"]
为 null 但您尝试使用 DefaultView
您将得到 object reference
(ds.Tables["DATA"]
) is not set to instance of an object
- 因为它是空的。
如果你的方法中的所有对象都是必需的,你应该抛出一些异常或适当地处理它们;
if (clsFoldingManagement == null) throw new Exception ("The class is not initialized");
if (ds.Tables["DATA"] == null) throw new Exception ("The DATA table in the dataset is not initialized");
if (cbUpdateProject.SelectedValue == null) throw new Exception ("The combobox selected value is not initialized");
cbUpdateItemName.DataSource = null;
//DataSet data = clsFoldingManagement.fetchProjectDetails();
DataSet ds = clsFoldingManagement.fetchProjectsForUpdateQty(int.Parse(cbUpdateProject.SelectedValue.ToString()));
cbUpdateProject.DataSource = ds.Tables["DATA"].DefaultView;
cbUpdateProject.DisplayMember = "ProjectName";
cbUpdateProject.ValueMember= "Client_ID";
我在名为 clsFoldingManagement
的 class 中创建了方法名称 fetchProjectsForUpdateQty
。在通过函数(以数据集的形式)返回值数据时,我在 winform 组合框中收到错误消息,指出对象引用未设置为对象实例。下面是我在 class clsFoldingManagement
fetchProjectsForUpdateQty
代码
public static DataSet fetchProjectsForUpdateQty(int client_id)
{
using (var con = new SqlConnection(ConStr))
{
string query = "select tblClient.ProjectName, tblFolding.Name , tblFolding.FoldingID from tblStockManagement LEFT OUTER JOIN tblClient ON tblClient.Client_ID=tblStockManagement.Client_ID LEFT OUTER JOIN tblFolding ON tblFolding.FoldingID=tblStockManagement.Client_ID where tblStockManagement.client_id=@clientid and tblStockManagement.quantity >0";
using (var cmd = new SqlCommand(query, con))
{
con.Open();
cmd.Parameters.Add("@clientid", SqlDbType.Int).Value = client_id;
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, con);
DataSet ds = new DataSet();
da.Fill(ds, "DATA");
return ds;
}
}
}
并且我在我的组合框点击事件中编写了以下代码 (cbUpdateProject_Click
)
cbUpdateItemName.DataSource = null;
//DataSet data = clsFoldingManagement.fetchProjectDetails();
DataSet ds = clsFoldingManagement.fetchProjectsForUpdateQty(int.Parse(cbUpdateProject.SelectedValue.ToString()));
cbUpdateProject.DataSource = ds.Tables["DATA"].DefaultView;
cbUpdateProject.DisplayMember = "ProjectName";
cbUpdateProject.ValueMember= "Client_ID";
这是我得到的异常详细信息:
System.NullReferenceException was unhandled
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=FazalConstructions
StackTrace:
at FazalConstructions.frmStockMoving.cbUpdateProject_Click(Object sender, EventArgs e) in e:\Waqas Folder\FazalConstruction\FazalConstructions\FazalConstructions\frmStockMoving.cs:line 87
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.ComboBox.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at FazalConstructions.Program.Main() in e:\Waqas Folder\FazalConstruction\FazalConstructions\FazalConstructions\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
object reference is not set to an instance of object
是我最喜欢抛出的错误之一,它的意思正是它所说的。您在代码中引用的对象未设置为对象的实例。
首先,最好确定哪一行代码引发了异常。
然后分析行中的对象并确保它们不为空。如果您说 cbUpdateProject.DataSource = ds.Tables["DATA"].DefaultView;
并且 ds.Tables["DATA"]
为 null 但您尝试使用 DefaultView
您将得到 object reference
(ds.Tables["DATA"]
) is not set to instance of an object
- 因为它是空的。
如果你的方法中的所有对象都是必需的,你应该抛出一些异常或适当地处理它们;
if (clsFoldingManagement == null) throw new Exception ("The class is not initialized");
if (ds.Tables["DATA"] == null) throw new Exception ("The DATA table in the dataset is not initialized");
if (cbUpdateProject.SelectedValue == null) throw new Exception ("The combobox selected value is not initialized");
cbUpdateItemName.DataSource = null;
//DataSet data = clsFoldingManagement.fetchProjectDetails();
DataSet ds = clsFoldingManagement.fetchProjectsForUpdateQty(int.Parse(cbUpdateProject.SelectedValue.ToString()));
cbUpdateProject.DataSource = ds.Tables["DATA"].DefaultView;
cbUpdateProject.DisplayMember = "ProjectName";
cbUpdateProject.ValueMember= "Client_ID";