可能是个愚蠢的问题,但是如何设置 C# 按钮的标签? (双窗体)

Might be a silly question, but how do you set the label of a c# button ? (winforms)

如何设置按钮的标签?

这是我的代码:

private void InitializeMyButton()
{
    // Create and initialize a Button.
    Button button1 = new Button();
 
    // Set the button to return a value of OK when clicked.
    button1.DialogResult = DialogResult.None;
 
    // Add the button to the form.
    Controls.Add(button1);
}

希望有人能找到解决办法。

来自 Control

类 有一个 Text 属性 你可以为此设置,还有一个 Button 就是其中之一。某些控件(如 Button 和 Label)的文本不是由用户设置的,而是由开发人员设置的。其他 (TextBox) 是用户可编辑的,您可以从文本 属性 中读取以找出用户输入的内容

有些控件并没有真正合理地使用 Text 属性(例如 DataGridView),但它们派生自 Control,因此它们有一个(未使用)

在 C# 中,属性 就像一个变量:您可以通过将其放在 = 的左侧来为其设置一个值:

label.Text = "Hello";

您也可以阅读它们:

MessageBox.Show("You typed " + textbox.Text);

方法和属性不同;方法“做某事”; .Show 以上是一种方法;它显示一个 MessageBox,您将一个字符串作为参数传递给它,但它与 属性.

不同

您没有通过调用 (运行) 来设置 属性 - 如果按钮具有文本 方法,您在评论 button.Text("My button label") 中的尝试将起作用,但是按钮上的 Text属性,不是方法..

当您在大多数情况下查看 C# 时,您可以通过查看其后是否有左括号 ( 来判断某物是 属性 还是方法。方法也有动词名称,而属性是名词:

textbox.Clear(); 
textbox.Text = "hello";
textbox.AppendText("world");

Button.Text:

private void InitializeMyButton()
{
    // Create and initialize a Button.
    Button button1 = new Button();
 
    // Set the button to return a value of OK when clicked.
    button1.DialogResult = DialogResult.None;

    button1.Text = "OK"; 

    // Add the button to the form.
    Controls.Add(button1);
}