错误消息“非静态字段,方法或属性需要对象引用". [英] Error message "An object reference is required for the non-static field, method or property."

查看:116
本文介绍了错误消息“非静态字段,方法或属性需要对象引用".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个程序来访问数据库.

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.

主要表单代码段:

 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);

    }

辅助表格代码段:

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;
        }


    }

我的辅助代码段旨在使用循环将所有数据填充到文本框中,而无需我手动写出每个tb00.Text = data []等.由于最需要静态方法,因此我最有可能无法访问C#中的FindControls()方法.主窗体中使用的P类执行SQL代码,并且可以正常工作.

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. :)

推荐答案

如果 getData() MemForm 中的非静态方法,则需要 MemForm 来使用它.您有一个: MemForm mem = new MemForm(); 使用作为 MemForm 实例的 mem 对象.

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);

这篇关于错误消息“非静态字段,方法或属性需要对象引用".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆