如何获取更新的 2 个文本框中的值的总和 C#
how to get the sum of values in 2 textboxes that gets updated C#
我有 2 个定期更新的文本框,通过串行端口,每个文本框在 1 行上显示数据,我想从这些文本框中获取这些值的总和并将总和放入另一个文本框中。
代码:
value 1 and 2 are type string
textbox1.text = value1;
textbox2.text = value2;
double value3 = convert.ToDouble(value1) + convert.ToDouble(value2);
textbox3.text = value3.ToString();
输出文本框1:
100, after sometime updates to 200, then 300
输出文本框2:
50, after sometime updates to 100, then 150
我得到的,在文本框 3 中输出:
150, after some time updates to 300, then 450
我应该得到的值是
100+200+300+50+100+150
当您在 C# 中从文本字段获取输入时,您将获取字符串数据作为输入。对于整数运算,您需要使用 Parse
方法从文本转换字符串输入。
尝试
Int16.Parse()
Int32.Parse()
Int64.Parse()
解决了我自己的问题,生病了post以防其他人可能处于相同的位置
used two lists got the sums and added the sums
List<double> totalvalueList = new List<double>();
totalvalueList.Add(Convert.ToDouble(value1));
double totalval = totalvalueList.Sum();
希望对你有用
1) 在class级别下面声明:
List<double> txbxList1 = new List<double>();
List<double> txbxList2 = new List<double>();
2) 将以下代码与 textbox1 和 textbox2 的 TextChanged 事件一起使用
private void textBox1_TextChanged(object sender, EventArgs e)
{
txbxList1.Add(double.Parse(textBox1.Text));
textBox3.Text = sumList().ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
txbxList2.Add(double.Parse(textBox2.Text));
textBox3.Text = sumList().ToString();
}
private double sumList()
{
double sum = 0;
foreach(double d in txbxList1)
{
sum += d;
}
foreach (double d in txbxList2)
{
sum += d;
}
return sum;
}
我有 2 个定期更新的文本框,通过串行端口,每个文本框在 1 行上显示数据,我想从这些文本框中获取这些值的总和并将总和放入另一个文本框中。
代码:
value 1 and 2 are type string
textbox1.text = value1;
textbox2.text = value2;
double value3 = convert.ToDouble(value1) + convert.ToDouble(value2);
textbox3.text = value3.ToString();
输出文本框1:
100, after sometime updates to 200, then 300
输出文本框2:
50, after sometime updates to 100, then 150
我得到的,在文本框 3 中输出:
150, after some time updates to 300, then 450
我应该得到的值是
100+200+300+50+100+150
当您在 C# 中从文本字段获取输入时,您将获取字符串数据作为输入。对于整数运算,您需要使用 Parse
方法从文本转换字符串输入。
尝试
Int16.Parse()
Int32.Parse()
Int64.Parse()
解决了我自己的问题,生病了post以防其他人可能处于相同的位置
used two lists got the sums and added the sums
List<double> totalvalueList = new List<double>();
totalvalueList.Add(Convert.ToDouble(value1));
double totalval = totalvalueList.Sum();
希望对你有用
1) 在class级别下面声明:
List<double> txbxList1 = new List<double>();
List<double> txbxList2 = new List<double>();
2) 将以下代码与 textbox1 和 textbox2 的 TextChanged 事件一起使用
private void textBox1_TextChanged(object sender, EventArgs e)
{
txbxList1.Add(double.Parse(textBox1.Text));
textBox3.Text = sumList().ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
txbxList2.Add(double.Parse(textBox2.Text));
textBox3.Text = sumList().ToString();
}
private double sumList()
{
double sum = 0;
foreach(double d in txbxList1)
{
sum += d;
}
foreach (double d in txbxList2)
{
sum += d;
}
return sum;
}