在 Page1.aspx 上,我有 3 个带有比较验证器的 txtBox,以确保它们的类型为货币。
在 Page2.aspx 上,我有另一个名为 txtResult 的文本框,其作用是当在 Page1 上单击 btnCalculate 时显示其他 3 个 txtBox 的总和。
问题:我无法将 3 个 txtBox 视为 double 而不是字符串。如果 txtBox 值为 1、3 和 8,则 txtResult 将为 138 而不是 12。
我尝试解析,但不允许编译失败。
Page1 背后的代码:
protected void btnCalculate_Click(object sender, EventArgs e)
{
if (IsValid)
{
Server.Transfer("Page2.aspx");
}
}
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;
}
尝试使用TryParse
:
txtResult.Text =
double.TryParse(((TextBox)lastPage.FindControl("txtGross")).Text, out gross);
错误:
Cannot implicitly covert bool to string
最佳答案
您可以使用 Double.Parse(text) 将文本转换为 double 型。例如:
txtResult.Text = (Double.Parse(((TextBox)lastPage.FindControl("txtGross")).Text)
+ Double.Parse(((TextBox)lastPage.FindControl("txtValueOfAssets")).Text)
+ Double.Parse(((TextBox)lastPage.FindControl("txtInvestments")).Text)).ToString();
请注意,我需要将整个内容包装在 .ToString() 中以将答案转换回文本,以便可以将其分配给 txtResult.Text
。我在长语句中提供了答案,因为问题使用了一个长语句,但通常我将每个值转换为 double 并将它们放入单独的双变量中,然后我将它们添加到另一个语句中,最后在另一个语句中我会将答案转换为字符串并将其放入文本框中。我发现这种多语句方法更容易阅读和消化,但这只是个人喜好。
关于c# - 如何检索多个txtBox的值并在新页面中显示总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41967268/