如何通过单击按钮执行方法

时间:2020-06-01 10:25:52

标签: c# button methods

如何将功能添加到将运行我创建的方法的按钮上。我想通过按一下按钮将一个数组写到消息对话框中,但是我似乎什么都没走,所以我转向stackoverflow寻求帮助,因为谷歌搜索并不能真正解决我的问题。

 static void Tractors(Tractor[] tractors)
    {


        for (int i = 0; i < tractors.Length; i++)
        {
            Console.WriteLine((i + 1) + ", " + tractors[i].ToString());
        }
    }

这是我写出“拖拉机”表的函数。

 private void button1_Click(object sender, EventArgs e)
        {

        }

我应该在button1_click方法中写入什么内容才能使其起作用?

2 个答案:

答案 0 :(得分:0)

您需要将事件处理程序与按钮控件绑定,并在该事件处理程序中编写逻辑。如果是Windows窗体应用程序,则可以这样做。

this.button1 = new System.Windows.Forms.Button();
this.button1.Click += new System.EventHandler(this.button1_Click);

private void button1_Click(object sender, EventArgs e)
{
//Call your methods here
}

答案 1 :(得分:0)

您将以与呼叫Tractor()完全相同的方式呼叫Console.WriteLine()。两者都是静态函数。

但是该功能完全被搞砸了,很可能无法挽救。专有名称为printTractorsToConsole()。由于它包含Console.WriteLine()调用,因此它与控制台应用程序紧密相连-避免将功能绑定到一种显示技术上。

您需要一个更通用的函数来创建并返回一个字符串。然后,您可以将该字符串发送到WriteLine(),将其分配给Label.Text您希望将该字符串作为其他任何地方。字符串主要是用于输入或输出给用户的-太多的方法可以将其传递给用户。

//Not tested against a compiler, may contain syntax errors
static string TractorArrayToString(Tractor[] tractors){
    string output = "";

    for (int i = 0; i < tractors.Length; i++)
    {
        output += (i + 1) + ", " + tractors[i].ToString()) + Environment.NewLine;
    }

    return output;
}

但是即使函数也可能不是一个好主意,因为该函数会将所有表示形式绑定为一种格式。通常,您可以将该循环直接写入Click事件。但是此功能看起来像是出于调试目的而打印的,所以它可能起作用。