[英]An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in the user code
[英]An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
我试图将 dropDown 的值乘以用户在 daysRenting 中输入的值。 我收到有关正在使用的数据类型的格式错误。 dropDown 使用双精度数,而 daysRenting 是一个整数。 我的问题在于这行代码......我如何重写它以将我的数据转换为所需的形式? 结果将是双重的。 下拉值是所选汽车的每日费用。
protected void button_Click(object sender, EventArgs e)
{
int i = Convert.ToInt32(dropDown.SelectedItem.Value.ToString()) * Convert.ToInt32(daysRenting.Text.ToString());
totalCost.Text = i.ToString();
}
这是完整的代码供参考。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Assignment5.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="dropDown" runat="server" AutoPostBack="True" OnSelectedIndexChanged="dropDown_SelectedIndexChanged">
<asp:ListItem Value="null">Pick A Car Type</asp:ListItem>
<asp:ListItem Value="29.99">Compact</asp:ListItem>
<asp:ListItem Value="34.99">Intermediate</asp:ListItem>
<asp:ListItem Value="24.99">Economy</asp:ListItem>
<asp:ListItem Value="44.99">Standard</asp:ListItem>
<asp:ListItem Value="49.99">Full Size</asp:ListItem>
</asp:DropDownList>
<br/><br/>
Days Renting:<asp:TextBox ID="daysRenting" width="150px" runat="server" </asp:TextBox>
<br /><br/>
</div>
<asp:Button ID="button" runat="server" Text="Submit" OnClick="button_Click" />
<br/><br/>
Total Cost:<asp:TextBox ID="totalCost" ReadOnly="true" runat="server" OnTextChanged="totalCost_TextChanged"></asp:TextBox>
</form>
</body>
</html>
这是 .cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Assignment5
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void dropDown_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void button_Click(object sender, EventArgs e)
{
int i = Convert.ToInt32(dropDown.SelectedItem.Value.ToString()) * Convert.ToInt32(daysRenting.Text.ToString());
totalCost.Text = i.ToString();
}
protected void totalCost_TextChanged(object sender, EventArgs e)
{
}
}
}
您无法将下拉列表中double
值的那些字符串表示直接解析为int
,因此会出现错误。 在内部,它基本上是这样调用的,它需要一个整数:
Int32.Parse("29.99", NumberStyles.Integer, CultureInfo.CurrentCulture);
将字符串转换为double
,然后像这样使用它们或将它们转换为int
。
double i =
Convert.ToDouble(dropDown.SelectedItem.Value) * Convert.ToInt32(daysRenting.Text);
totalCost.Text = i.ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.