Error message “An object reference is required for

2019-09-22 11:03发布

问题:

I am creating a program to access a database.

The code that is causing me trouble is meant to open a new form when a button is pressed. It then gets data based on the selected values in a listbox on the main form and is needed to send that data to the second form to be placed in textboxes and labels.

The problem I have, is that in order for the code to execute without throwing the Error

"An object reference is required for the non-static field, method or property..."

I must make the method in the secondary form static; however this prevents me from accessing the controls on the secondary form.

Main Form Code Snippet:

 private void MemView_Click(object sender, EventArgs e)
    {
        string selected = lstMember.SelectedItems[0].Text;
        //MessageBox.Show(selected);
        string[] data = P.selectMem(selected);
        MessageBox.Show(data[0]);

        MemForm mem = new MemForm(); //How to open a designed form

        mem.Show();  //Displays the addmem form

        MemForm.getData(data);

    }

Secondary Form Code Snippet:

public void getData(string[] Data)
    {
        int index = 0;
        bool loop = false;
        string text;

        while (loop == true)
        {
            if (index < 10)
            { text = "tb0" + index.ToString(); }
            else
            { text = "tb" + index.ToString(); }

            index = index + 1;
        }


    }

My secondary code snippet is meant to use the loop to fill all the data into the textboxes without me having to manually write out each tb00.Text = data[] etc. I am unable to access the FindControls() method in C# most likely due to the need for a static method. The P class used in the Main Form performs the SQL code and is working fully.

I've tried to give enough information for an answer, however if more is needed just ask in a comment I will try and provide more. :)

回答1:

If getData() is a non-static method in MemForm, you need an instance of MemForm to use it. You have one: MemForm mem = new MemForm(); Use the mem object which is an instance of MemForm.

mem.getData(data);