简体   繁体   中英

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. I'm passing usernames from DataGridView to second form using code:

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. I'm adding data to listBoxItems manually. NullReferenceException occur on a button click, here:

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. 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. 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!");
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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