如何使用静态函数更改按钮文本?

时间:2010-09-26 09:40:25

标签: .net

我需要使用静态函数更改按钮文本。

static string[] ARRay = new string[10];
[STAThread]
static void Main()
{
    string[] args = Environment.GetCommandLineArgs();
    for (int i = 1; i != args.Length; ++i)
    {
        command(i.ToString());
        ARRay[0] = i.ToString(); 
    }
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

static void command(string line)
{
    button1.Text = ARRay[0]; // here error
}

3 个答案:

答案 0 :(得分:0)

在按钮存在之前,您无法更改按钮的文本。

您必须首先启动应用程序,或至少创建它将使用的表单,然后您可以获得对该按钮的引用并将其存储在静态变量中,您可以从静态方法到达它。 / p>

答案 1 :(得分:0)

首先,button1似乎是Form Form1的成员。您需要首先在Form1方法中存储Main实例,方法是首先声明static成员:

static Form1 myForm;

然后创建该实例并将其传递给Run的{​​{1}}方法:

Application

执行此操作后,您将有两个选择: 1.如果myForm = new Form1(); Application.Run(myForm); button1 public,您可以在Button方法中使用此行:

command

或2.您可以在myForm.button1.Text = ARRay[0]; public中声明Form1方法来更新class

答案 2 :(得分:0)

button1是静态的吗?它应该是在静态方法中使用它。请查看this article了解详情。