简体   繁体   English

NullReferenceException使用两个构造函数类

[英]NullReferenceException using two constructor class

I'm new here. 我是新来的。 I can't find solution to my problem anywhere. 我在任何地方都找不到解决问题的方法。 I'm writing a project to school. 我正在写一个上学的项目。 I have two forms. 我有两种形式。 In first form, I have a DataGridView object, when I'm storing data in a SQL Server database. 在第一种形式中,当我在SQL Server数据库中存储数据时,我有一个DataGridView对象。 I'm passing usernames from DataGridView to second form using code: 我使用代码将用户名从DataGridView传递到第二种形式:

List<string> usersList = new List<string>();

for (int i = 0; i < dataGridViewUsers.RowCount; i++)
{
    usersList.Add(dataGridViewUsers.Rows[i].Cells[1].Value.ToString());
}

AddFileForm addFile = new AddFileForm(usersList);
addFile.Show();

In second form in have following code: 在第二种形式中具有以下代码:

    private List<string> userNames;
    private Files file;

    public AddFileForm()
    {
        file = new Files();
        userNames = new List<string>();
        InitializeComponent();
    }

    public AddFileForm(List<string> _userNames)
    {
        this.userNames = _userNames;
        InitializeComponent();
        listBoxUserList.DataSource = _userNames;
    }

    private AddFileForm(Files _file)
    {
        this.file = _file;
        InitializeComponent();
        listBoxUserList.SelectedValue = _file.userName;
        listBoxItems.SelectedValue = _file.directory;
    }

Passing data from first form works fine, but the problem starts when I try to pass data from listBoxUserList and listBoxItems to database using stored-procedures. 从第一种形式传递数据可以正常工作,但是当我尝试使用存储过程将数据从listBoxUserList和listBoxItems传递到数据库时,问题就开始了。 I'm adding data to listBoxItems manually. 我正在手动将数据添加到listBoxItems。 NullReferenceException occur on a button click, here: NullReferenceException发生在单击按钮时,在这里:

private void buttonAdd_Click(object sender, EventArgs e)
{
    if (listBoxUserList.SelectedItems.Count != 0 && listBoxItems.SelectedItems.Count != 0)
    {
            file.userName = listBoxUserList.SelectedValue.ToString();
            file.directory = listBoxItems.SelectedValue.ToString();
                try
                {
                    DBConnection connection = new DBConnection();
                    connection.AddFile(file);

                    MessageBox.Show("File added to database.");
                }
                catch (Exception)
                {
                    MessageBox.Show("Failed database connection!");
                }
            }
            else
            {
                MessageBox.Show("First, select items to add to database");
            }
        }

Value from both listBoxes is not null, I have checked this. 来自两个listBoxes的值都不为null,我已经检查了这一点。 The main problem probably is in class constructor. 主要问题可能在类构造函数中。 My stored procedure works fine, when I was comment constructor who passing data from first form, it perfectly passing data to database. 我的存储过程运行良好,当我是注释构造函数的成员时,它从第一种形式传递数据,就完美地将数据传递给数据库。 So, what's wrong? 那怎么了 What i should do with constructors of class, it will work property in both cases? 我应该用类的构造函数做什么,在两种情况下都可以工作?

I'm pasting error details 我要粘贴错误详细信息

System.NullReferenceException was unhandled
  HResult=-2147467261
  Message=Odwołanie do obiektu nie zostało ustawione na wystąpienie obiektu.
  Source=FilesEncoding
  StackTrace:
       w FilesEncoding.AddFileForm.buttonAdd_Click(Object sender, EventArgs e) w C:\Users\Grabarz\Documents\Visual Studio 2010\Projects\FilesEncoding\FilesEncoding\AddFileForm.cs:wiersz 110
       w System.Windows.Forms.Control.OnClick(EventArgs e)
       w System.Windows.Forms.Button.OnClick(EventArgs e)
       w System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       w System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       w System.Windows.Forms.Control.WndProc(Message& m)
       w System.Windows.Forms.ButtonBase.WndProc(Message& m)
       w System.Windows.Forms.Button.WndProc(Message& m)
       w System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       w System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       w System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       w System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       w System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       w System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       w System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       w System.Windows.Forms.Application.Run(Form mainForm)
       w FilesEncoding.Program.Main() w c:\users\grabarz\documents\visual studio 2010\Projects\FilesEncoding\FilesEncoding\Program.cs:wiersz 18
       w System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       w System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       w Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       w System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       w System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       w System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

I'm not sure, is this code correct, but finally it start to work! 我不确定这段代码是否正确,但最终它开始起作用了! I've got similar solution, here but I don't know what's are diffrents between constructor in my topic question, and this. 我有类似的解决方案, 在这里 ,但我不知道是什么的是构造之间diffrents在我演讲的题目的问题,而这个。 In my opinion my first record should work perfectly too. 我认为我的第一张唱片也应该很完美。 Here's my code: 这是我的代码:

private string userName;
private string fileDirectory;

public AddFileForm(Files _file) : this(_file.userName, _file.directory) {  }
public AddFileForm(string user, string directory)
{
    userName = user;
    fileDirectory = directory;
    InitializeComponent();
}

private void buttonAdd_Click(object sender, EventArgs e)
{
    userName = listBoxUserList.SelectedItem.ToString();
    fileDirectory = listBoxItems.SelectedItem.ToString();
        try
        {
            Files file = new Files();
            file.userName = userName;
            file.directory = fileDirectory;
            DBConnection connection = new DBConnection();
            connection.AddFile(file);
        }
        catch (Exception)
        {
            MessageBox.Show("Failed database connection!");
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM