[英]C# Windows Form Application - How to take the users input from text boxes
I'm confused on what I'm supposed to use to get a users input.我对我应该用来获取用户输入的内容感到困惑。
I have 2 TextBoxes and a Button and I want to take what the user enters in those 2 TextBoxes and use it to calculate the total when the button is pushed.我有 2 个文本框和一个按钮,我想获取用户在这 2 个文本框中输入的内容,并在按下按钮时使用它来计算总数。
I already have 3 variables declared: one for 1st input, one for the 2nd input, and one for the total of the two.我已经声明了 3 个变量:一个用于第一个输入,一个用于第二个输入,一个用于两者的总和。
double length;
double width;
double area;
area =((length*length)+(width)(width));
I have this code inside of an event handler that will calculate the area when the Button is clicked.我在一个事件处理程序中有这个代码,它会在单击按钮时计算面积。 C# is new for me, I remember in Java you can use a scanner but I'm not sure what you can use here. C# 对我来说是新的,我记得在 Java 中你可以使用扫描仪,但我不确定你可以在这里使用什么。
The TextBox
control has a Text
property . TextBox
控件有一个Text
属性。 You would simply reference that to get the value out of the TextBox
.您只需引用它即可从TextBox
获取值。
Note that in the following example, I'm making assumptions about the names of your controls since you didn't provide them.请注意,在以下示例中,由于您没有提供控件的名称,因此我对控件的名称进行了假设。
private void CalculateBtn_Click(object sender, EventArgs e)
{
string lengthString = LengthTxt.Text;
string widthString = WidthTxt.Text;
}
You'll notice that the Text
property returns a string
.您会注意到Text
属性返回一个string
。 You'll need to parse that into a number to do the actual calculations.您需要将其解析为一个数字才能进行实际计算。 By using, for example, Double.Parse
or Double.TryParse
.例如,通过使用Double.Parse
或Double.TryParse
。
Since you're taking user input, you should use Double.TryParse
.由于您正在接受用户输入,因此您应该使用Double.TryParse
。 A TextBox
will take any string
, after all.毕竟,一个TextBox
将接受任何string
。 Not just string
s that parse to a double
.不仅仅是解析为double
string
。
private void CalculateBtn_Click(object sender, EventArgs e)
{
if (!double.TryParse(LengthTxt.Text, out double length))
{
MessageBox.Show("Please enter a number for the length.");
return;
}
if (!double.TryParse(Width.Text, out double width))
{
MessageBox.Show("Please enter a number for the width.");
return;
}
}
Click on one of the box and you should see the properties tab on the bottom right.单击其中一个框,您应该会看到右下角的属性选项卡。 Search for the (Name) property under "Design" and set a name such as "length".在“设计”下搜索(名称)属性并设置一个名称,例如“长度”。 In the EventHandler, get the string value with (the name of your box).Text and you can use a method such as Int32.Parse(string) to convert it to an int.在 EventHandler 中,使用(您的框的名称)获取字符串值。Text,您可以使用诸如 Int32.Parse(string) 之类的方法将其转换为 int。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.