[英]How to show Web Browser in Visual Studio 2019 Windows Forms Application?
[英]Visual Studio Windows Application - Show numbers in label
我正在嘗試制作一個簡單的增量游戲。 我有一個“建造小屋”的按鈕。 基本上,每次按下 int 值時都將其加 1。 然后我想在標簽中顯示建造了多少小屋。 但是 label1.Text 只接受字符串值。
但是,當我轉換整數 .ToString 時,它不起作用。 它將數字保持在 1 並且不增加它。
public void Button1_Click(object sender, EventArgs e)
{
int numberofhuts = 0;
numberofhuts++;
label1.Text = numberofhuts;
}
這就是它的樣子。 任何幫助將不勝感激。
現在,每次單擊按鈕時,您都將變量numberofhuts
重置為零(正如其他人指出的那樣)。 所以你需要做以下兩件事之一:
第二種方法可能不是最好的,因為這需要某種機制來確保標簽文本始終是數字。 所以你可以做這樣的事情:
public partial class MyForm : Form
{
// Constructor (normally generated by Visual Studio)
public MyForm()
{
InitializeComponent();
}
// Create, and initialize the variable outside the method.
private int _numberOfHuts = 0;
// When clicking the button, the variable is incremented
// and the label is updated with the new value.
private void Button1_Click(object sender, EventArgs e)
{
_numberOfHuts++;
label1.Text = numberOfHuts.ToString();
}
}
此外,您應該考慮您的命名。 像Button1
和Label1
這樣的名稱是糟糕的選擇,因為它們絕不表明它們的對象功能是什么。 而是使用類似IncrementHutCount
的按鈕和NumberOfHuts
的東西作為標簽。
編輯:請注意,我所做的范圍更改可能不夠廣泛。 我只是假設你只有一個形式,它在程序的整個生命周期中都存在。 如果不是這種情況,您需要將其移動到其他地方。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.