我有4个文本框,我想把值放入,我希望它从输入值的值到4(或更多)文本框中找到平均数。
我希望平均值显示在一个只读框中(richtextbox对此有用吗?)。
答案 0 :(得分:0)
您可以同时使用RichTextBox和普通TextBox。要确保它是只读的,请在设计器页面中执行以下操作;
Select the TextBox > Scroll under properties window > Behavior Section > Read-Only property
将此属性设置为true将使TextBox不可由用户编辑。
在有4个可编辑的TextBox和1个不可编辑的文本框之后,您可以实现类似下面的内容来添加TextBoxes的数值并将其显示在只读TextBox中。
private void AverageAndDisplay()
{
try
{
//Convert values to numeric
decimal one = Convert.ToDecimal(textBox1.Text);
decimal two = Convert.ToDecimal(textBox2.Text);
decimal three = Convert.ToDecimal(textBox3.Text);
decimal four = Convert.ToDecimal(textBox4.Text);
//Find the average
decimal average = (one + two + three + four) / 4.0m;
//Show the average, after formatting the number as a two decimal string representation
textBox5.Text = string.Format("{0:0.00}", average);
}
catch(Exception e) //Converting to a number from a string can causes errors
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
答案 1 :(得分:0)
所以你应该采取以下步骤:
Value1Txt
,Value2Txt
,Value3Txt
,Value4Txt
AverageValueLbl
在OnClick
上附加CalculateAverageBtn
个活动。您可以使用按钮的签名OnClick =" CalculateAverageBtn_Click"或者在代码中执行
//this should be inside InitializeComponents method
CalculateAverageBtn.OnClick += CalculateAverageBtn_Click;
protected void CalculateAverageBtn_Click(object sender, EventArgs e)
{
//...code
}
现在,在CalculateAverageBtn_Click的正文中,您应该解析TextBoxes的值并计算平均值。您可以使用decimal.TryParse
方法
decimal value1 = 0;
if(!decimal.TryParse(Value1Txt.Text, out value1)
{
//if you come in this if the parsing of the value is not successful so
you need to show error message to the user. This happen when the user
enters text like 123Test, this is not a number. So you need to show
error message
}
创建一个标签,您将在其中显示错误消息。我们称之为ErrorLbl。因此,当解析不成功时,我们将在此标签中写入错误消息。
if(!decimal.TryParse(Value1Txt.Text, out value1)
{
ErrorLbl.Text = "The value of value 1 textbox is not valid number"
return; //exit the button click method
}
计算4个文本框的平均值并将其写入AverageValueLbl
。这应该是按钮事件点击
AverageValueLbl.Text = (value1+value2+value3+valu4)/4.ToString();
尝试了解您在做什么,不要盲目地复制/粘贴代码。这几乎是初学者编程。这肯定是家庭作业,所以尽量去理解它,因为在将来更难的作业中你会丢失。