错误:"输入字符串格式不正确"在虚假陈述

时间:2014-05-01 20:25:27

标签: c# asp.net tryparse

如果语句(numtickets> tickav)为true,我的代码工作正常(如果可用的票证大于订购的票证)但是如果是其他方式,则会抛出此错误“用户代码未处理FormatException,输入字符串为不正确的格式“on int numTick = Convert.ToInt32(txtNumberOfTickets.Text); 我知道我可以使用tryparse,我需要帮助将它放在代码中。 任何帮助将不胜感激,谢谢

 namespace TicketsApp
 {
 public partial class TicketOrder : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["description"] != null && Session["EventID"] != null &&                             Session["numtickets"] != null && Session["ticketcost"] != null
            && Session["State"] != null && Session["Section"] != null && Session["Row"] != null && Session["date"] != null)
        {
            if (!IsPostBack)
            {
                try
                {
                    txtEventDescription.Text = Session["description"].ToString();
                    txtEventID.Text = Session["EventID"].ToString();
                    txtTicketsAvailable.Text = Session["numtickets"].ToString();
                    txtTicketCost.Text = Session["ticketcost"].ToString();
                    txtState.Text = Session["State"].ToString();
                    txtSectionNumber.Text = Session["Section"].ToString();
                    txtRowNumber.Text = Session["Row"].ToString();

                    txtNumberOfTickets.Focus();
                    lblOutput.Visible = false;

                }
                catch
                {
                    lblError.Text = "Please Search for Tickets First!";
                    lblError.Visible = true;
                    btnOrderTickets.Visible = false;
                    Response.Redirect("TicketSearch.aspx");
                    return;
                }
            }
        }
    }


    protected void btnOrderTickets_Click(object sender, EventArgs e)
    {

        TicketsDataAccessDataContext NewOrder = new TicketsDataAccessDataContext();

        int numTick = Convert.ToInt32(txtNumberOfTickets.Text);
        string s = txtTotalCost.Text.Substring(1);
        int totc = Convert.ToInt32(s);
        int id = Convert.ToInt32(txtEventID.Text);
        DateTime dt = Convert.ToDateTime(Session["date"]);

        int returnedValue = NewOrder.PlaceOrderFull(id, txtEventDescription.Text, dt, Session["State"].ToString(), Session["section"].ToString(), Session["Row"].ToString(), numTick, totc, "vfateev");
        if (returnedValue != 0)
        {
            lblOutput.Text = "Error has occured. Please try again";
            lblOutput.Visible = true;
            btnOrderTickets.Visible = false;
        }
        else
        {
            lblOutput.Visible = true;
            lblOutput.Text = "Thank you";
            btnOrderTickets.Visible = false;
        }

    }

    protected void txtNumberOfTickets_TextChanged1(object sender, EventArgs e)
    {
        int cos = Convert.ToInt32(txtTicketCost.Text);
        int numtickets = Convert.ToInt32(txtNumberOfTickets.Text);
        int tickav = Convert.ToInt32(txtTicketsAvailable.Text);

        if (numtickets > tickav)
        {
            lblError.Text = "Please Enter a valid ticket quantity";
            lblError.Visible = true;

            lblOutput.Text = "";
            txtNumberOfTickets.Text = "";
        }


        else
        {

            int cost = cos * numtickets + 5;
            txtTotalCost.Text = "$" + cost.ToString();
            lblOutput.Visible = false;
            lblFee.Text = "There is a $5 shipping fee";
            lblFee.Visible = true;
            lblError.Text = "";}
    }
}

}

3 个答案:

答案 0 :(得分:1)

您可以使用返回布尔值的int.TryParse并且不会抛出异常。

int numTick = 0;
bool result = int.TryParse(txtNumberOfTickets.Text, out numTick );

您还可以执行一些客户端验证,以确保填写该字段并包含数字。

答案 1 :(得分:0)

只需使用类似的东西 要在C#中使用IsNumeric,请添加对Microsoft.VisualBasic.dll的引用,然后

if (Information.IsNumeric(value))
   {
    DoSomthing();
   }
   else
   {
    DoSomethingElse();
   }

<强>更新 OPEN VISUAL STUDIO ==&gt;你的项目

单击解决方案并添加引用,选择Microsoft.VisualBasic.dll confrim将新引用添加到您对项目的引用中。

转到页面顶部并声明Microsoft.VisualBasic.dll别名的导入statemnet

using Microsoft.VisualBasic.dll;

然后您需要检查文本框的值

 if (Information.IsNumeric(yourtextbox.text.trim()))
   {
    //case true alias your value is numeric 
        //do what you need here like assing value to a var or any
        //else
   }
   else
   {
         //put your logic here in case result is false and value 
         //is not numeric
   }

答案 2 :(得分:0)

这是使用Int32.TryParse重写的方法之一。我假设您正在使用txtTotalCost.Substring(1)来修剪货币符号。可能有安全的方法来做到这一点,我只是要修剪&#34; $&#34;对于这个例子。

protected void btnOrderTickets_Click(object sender, EventArgs e)
{
    int numberOfTickets, ticketCost, eventId;
    if(Int32.TryParse(txtNumberOfTickets.Text, out numberOfTickets) &&
        Int32.TryParse(txtTotalCost.Text.TrimStart('$'), out ticketCost) &&
        Int32.TryParse(txtEventID.Text, out eventId))
    {
        DateTime dt = Convert.ToDateTime(Session["date"]);

        TicketsDataAccessDataContext NewOrder = new TicketsDataAccessDataContext();
        int returnedValue = NewOrder.PlaceOrderFull(eventId, txtEventDescription.Text, dt, Session["State"].ToString(), Session["section"].ToString(), Session["Row"].ToString(), numberOfTickets, ticketCost, "vfateev");
        if (returnedValue != 0)
        {
            lblOutput.Text = "Error has occured. Please try again";
            lblOutput.Visible = true;
            btnOrderTickets.Visible = false;
        }
        else
        {
            lblOutput.Visible = true;
            lblOutput.Text = "Thank you";
            btnOrderTickets.Visible = false;
        }
    }
    else
    {
        lblOutput.Visible = true;
        lblOutput.Text = "Some validation error message here...";
    }
}

您需要对txtNumberOfTickets_TextChanged1进行类似的修改,以确保用户输入了有效的文字。