I have 2 textboxes that get updated regularly, via serial port each of them displays data on 1 line, I want to get the sum of these values from these textboxes and put the sum into another text box.
Code:
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();
Output textbox1:
100, after sometime updates to 200, then 300
Output textbox2:
50, after sometime updates to 100, then 150
What I'm getting, output in textbox3:
150, after some time updates to 300, then 450
The value I should get is
100+200+300+50+100+150
solved my own problem, ill post here in case someone else might be in the same position
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();
I hope it will work for you
1) Declare below at class level:
List<double> txbxList1 = new List<double>();
List<double> txbxList2 = new List<double>();
2) Use below code with the TextChanged event for both textbox1 and textbox2
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;
}
When you are getting input from text field in C# you will get string data as input. For integer operations, you need to convert your string input from text using Parse
method.
Try
Int16.Parse()
Int32.Parse()
Int64.Parse()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.