On Page1.aspx I have 3 txtBoxes with Compare Validators that ensure they are of type Currency.
On Page2.aspx I have another text box called txtResult whose job it is to display the sum of the other 3 txtBoxes when btnCalculate is clicked on Page1.
Problem: I can't get the 3 txtBoxes to be treated as doubles and not strings. If txtBox values are 1, 3, and 8, txtResult will be 138 and not 12.
I tried try parsing but it wasn't allowed failed to compile.
Code behind Page1:
protected void btnCalculate_Click(object sender, EventArgs e)
{
if (IsValid)
{
Server.Transfer("Page2.aspx");
}
}
Code behind Page2:
if (!IsPostBack)
{
Page lastPage = (Page)Context.Handler;
txtResult.Text = ((TextBox)lastPage.FindControl("txtGross")).Text
+ ((TextBox)lastPage.FindControl("txtValueOfAssets")).Text
+ ((TextBox)lastPage.FindControl("txtInvestments")).Text;
}
Attempt to use TryParse
:
txtResult.Text =
double.TryParse(((TextBox)lastPage.FindControl("txtGross")).Text, out gross);
Errors with:
Cannot implicitly covert bool to string
You can use Double.Parse(text) to convert the text into a double. So for example:
txtResult.Text = (Double.Parse(((TextBox)lastPage.FindControl("txtGross")).Text)
+ Double.Parse(((TextBox)lastPage.FindControl("txtValueOfAssets")).Text)
+ Double.Parse(((TextBox)lastPage.FindControl("txtInvestments")).Text)).ToString();
Notice that I needed to wrap the whole thing in a .ToString() to convert the answer back to text so that it can be assigned to txtResult.Text
. I provided the answer in on long statement since the questions used one long statement but typically I convert each of the values to a double and place them in individual double vars then I'd add those in another statement, and finally in yet another statement I'd convert the answer to a string and place it in the text box. I find such a multi statement approach easier to read and digest, but that's just personal preference.