【问题标题】:Might be a silly question, but how do you set the label of a c# button ? (winforms)可能是一个愚蠢的问题,但是如何设置 c# 按钮的标签? (winforms)
【发布时间】:2022-01-08 04:44:27
【问题描述】:

如何设置按钮的标签?

这是我的代码:

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

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

【问题讨论】:

  • 你为什么不用button1.Text
  • button1.Text = "OK Button";
  • button1.Text = "有趣的名字";
  • 您清楚地找到了the docs,因为您的代码是直接从中提取的 - 您是否寻找过可能设置按钮的Text 的东西?
  • 术语很重要。标签是一个控件。按钮也是如此。两者都有一个 .Text 属性。

标签: c# winforms button


【解决方案1】:

Control 继承的类有一个Text 属性,您可以为此设置,Button 就是其中之一。按钮和标签等一些控件有一个文本不是由用户设置的,只有开发人员设置的。其他(TextBox)是用户可编辑的,您可以从 Text 属性中读取以了解用户输入的内容

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

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

label.Text = "Hello";

您也可以阅读它们:

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

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

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

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

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

【讨论】:

  • 是的,但是当我尝试时,我使用了“button1.Text("text");"感谢您的帮助!
  • 这完全是一种 JavaScript 看待世界的方式。在 C# 中,属性就像变量:如果你想设置它们,它们会出现在 = 的左侧。我会澄清
【解决方案2】:

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

【讨论】:

  • 很简单,但显然它不在我的脑海中。非常感谢!
猜你喜欢
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 2011-08-24
  • 1970-01-01
  • 2013-02-04
相关资源
最近更新 更多