C# 单击按钮时如何在标签中显示结果?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2131570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display a result in a label when I click onto a button?
提问by Abid
On my GUI (Graphical User Interface), I have a button named Enter and a label.
When I click Enter
, I want my result to be shown in the label. How do I do that?
在我的 GUI(图形用户界面)上,我有一个名为 Enter 的按钮和一个标签。
当我单击 时Enter
,我希望我的结果显示在标签中。我怎么做?
回答by Oded
In winforms or webforms:
在 winforms 或 webforms 中:
label.Text = Enter.Text;
回答by Sam Holder
Double click on the button in the designer. This should create you a handler function for the buttons click event, something like this:
双击设计器中的按钮。这应该为按钮单击事件创建一个处理函数,如下所示:
private void Button_Click(object sender, EventArgs e)
{
}
then in the function add the code to set the text of the lable:
然后在函数中添加代码来设置标签的文本:
lable.Text = myResult;
you should end up with something like this:
你应该得到这样的结果:
private void Button_Click(object sender, EventArgs e)
{
lable.Text = myResult;
}
As you said you have an int which is a percentage, and you have the value 0, I suspect that you are having problems getting the percentage not writing the value to the lable. so you might want to look at this questionas I suspect that you have something like:
正如您所说,您有一个整数,它是一个百分比,并且您的值为 0,我怀疑您在获取百分比时遇到了问题,而不是将值写入标签。所以你可能想看看这个问题,因为我怀疑你有这样的事情:
int valuea;
int valueb;
int result= valuea/valueb*100;
in this example if valuea=45 and valueb=100 the value of result will be 0, not 45.
在此示例中,如果 valuea=45 和 valueb=100,则结果的值将为 0,而不是 45。
回答by Anders
For windows forms use the .Text property on the label:
对于 Windows 窗体,请使用标签上的 .Text 属性:
private void btnEnter_Click(object sender, EventArgs e)
{
int themeaningoflifeuniverseandeverything = 420 / 10;
lblResult.Text = themeaningoflifeuniverseandeverything.ToString();
}
See exampe: ButtonEvent.zip
参见示例:ButtonEvent.zip
回答by Pratik Deoghare
int result = 0; // declare a private variable to hold the result
// Event handler for Click of Enter button
private void Enter_Click(object sender, EventArgs e)
{
result = Add(10,20); // set result to result of some function like Add
label.Text = result.ToString();
}
private int Add(int a, int b)
{
return a + b;
}
NOTE: I assume you are a beginner working with Winforms.
注意:我假设您是使用 Winforms 的初学者。
回答by Krishna Prasad
Double click on button to generate event and write following code
双击按钮生成事件并编写以下代码
private void Button_Click(object sender, EventArgs e)
{
lable1.Text = ur result; //result must be in string format otherwise convert it to string
}