【问题标题】:Accessing variables in other functions in C#在 C# 中访问其他函数中的变量
【发布时间】:2020-04-18 10:36:16
【问题描述】:

我最近在我的 Raspberry Pi(或 headmelted 的 Code-OSS)上安装了 Visual Studio Code,我已经将它与 mono“连接”以创建和运行 WinForms 应用程序。但是,我总是使用 Visual Studio 来创建 WinForms 应用程序,但我不知道如何将按钮和标签添加到 WinForms 应用程序。我住在中国,无法访问 Google 或 YouTube。我试过在 Bing 上搜索,但大多数网站都被屏蔽了。

编辑:我已经成功制作了一个窗口,但我似乎无法在其他功能中访问它...代码:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Program
{
    [STAThread]
    private static void clicked(object sender, EventArgs e){
        password = textbox.Text;
        if(password == "mypassword"){
            stateLabel.Text = "Password is correct";
        }else{
            stateLabel.Text = "Password is incorrect";
        }
    }
    public static void Main()
    {
        var window = new Form();
        window.Text = "Login";
        window.Height = 130;
        window.Width = 365;
        TextBox textbox = new TextBox();
        Label passwordLabel = new Label();
        Button passwordButton = new Button();
        Label stateLabel = new Label();

        stateLabel.Text = "Please enter your password";
        passwordLabel.Text = "Password";
        passwordButton.Text = "Login";

        passwordLabel.Location = new Point(25, 30);
        textbox.Location = new Point(125, 25);
        passwordButton.Location = new Point(260, 25);
        stateLabel.Location = new Point(125, 60);
        passwordButton.Click += new System.EventHandler(clicked);

        window.Controls.Add(textbox);
        window.Controls.Add(passwordLabel);
        window.Controls.Add(passwordButton);
        window.Controls.Add(stateLabel);
        Application.Run(window);
    }
}

当我运行它时,它只是给我一个错误,说“窗口”未在单击的函数中定义。

【问题讨论】:

    标签: c# winforms visual-studio-code


    【解决方案1】:

    您可以通过创建该控件的实例并将其添加到Controls 集合中以编程方式添加控件

    TextBox textbox = new TextBox();
    textbox.Location = new Point(25,25);
    this.Controls.Add (textbox);
    

    您可以通过类似的方式添加其他控件。

    要了解更多相关信息,您还可以查看this Microsoft docs

    【讨论】:

    • 您的代码有效!我必须将 System.Drawing.dll 添加到 mcs 编译器和 using System.Drawing。非常感谢!
    猜你喜欢
    • 2013-09-13
    • 2017-06-09
    • 2018-03-07
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    相关资源
    最近更新 更多