C# System.NullReferenceException,同时从类中的方法返回值

本文关键字:方法 返回值 System NullReferenceException | 更新日期: 2023-09-27 18:34:27

我在名为 clsFoldingManagement 的类中创建了方法名称fetchProjectsForUpdateQty。 在通过函数(以数据集的形式)返回值数据时,我在 winform 组合框中收到错误,即对象引用未设置为对象的实例。 下面是我在类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:

C# System.NullReferenceException,同时从类中的方法返回值

object reference is not set to an instance of object

我最喜欢的错误之一,它的意思正是它所说的。 在代码中引用的对象未设置为对象的实例。

首先,最好确定引发异常的代码行。

然后分析行中的对象并确保它们不为空。如果你说cbUpdateProject.DataSource = ds.Tables["DATA"].DefaultView;ds.Tables["DATA"]是空的,但你试图使用DefaultView你会得到object referenceds.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";