繁体   English   中英

为什么我的代码说System.FormatException:“输入字符串的格式不正确。” 当我将文本框留空并单击提交按钮时?

[英]Why does my code say System.FormatException: 'Input string was not in a correct format.' when I leave the text box blank and click the submit button?

我有一个ASP.NET Web表单,该表单在ID为“ pin”的文本框中输入用户输入的数字,并从SQL数据库中检索插入其他文本框中的值。 一切正常,除了如果我将图钉文本框保留为空白然后单击提交,它将返回System.FormatException:“输入字符串的格式不正确。” 我怎样才能解决这个问题? 我尝试了代码

if (string.IsNullOrEmpty(pin.Text) || pin.Text == "0")
            {
                //Alert user string is either null, empty or 0
                ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Please enter your pin');", true);
            }

关于如何解决此问题的任何建议?

这是我的完整代码供参考。

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;


namespace Test
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string connectionString = @"Data Source=DESKTOP-HOB2BSG\SQLEXPRESS;Initial Catalog=dogdata;Integrated Security=True";


        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                sqlCon.Open();
                SqlCommand sqlCmd = new SqlCommand("SELECT COUNT(*) from dbo.tUser where pin = @pin", sqlCon);
                sqlCmd.CommandType = System.Data.CommandType.Text;
                sqlCmd.Parameters.AddWithValue("@pin", Int32.Parse(pin.Text.Trim()));

                var count = (int)sqlCmd.ExecuteScalar();

                if (count > 0)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Collecting Data');", true);

                    // Insert IMEI, Sim, and DeviceNumber into corresponding textboxes
                    string sqlSelectQuery = "SELECT IMEI, Sim, DeviceNumber FROM dbo.tUser WHERE Pin =" + int.Parse(pin.Text);
                    SqlCommand cmd = new SqlCommand(sqlSelectQuery, sqlCon);
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                        IMEI.Text = (dr["IMEI"].ToString());
                        Sim.Text = (dr["Sim"].ToString());
                        DeviceNumber.Text = (dr["deviceNumber"].ToString());
                    }

                }
                if (string.IsNullOrEmpty(pin.Text) || pin.Text == "0")
                {
                    //Alert user string is either null, empty or 0
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Please enter your pin');", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Please enter your pin');", true);
                }
            }
        }

    }
}

首先,您需要先验证此字符串是否为有效的数字值,然后再将其转换为int,您可以在一行代码中做到这一点

您可以将测试Int32.TryParse(string.IsNullOrEmpty(pin.text) ? "0" : pin.text)到这样的一行,例如: Int32.TryParse(string.IsNullOrEmpty(pin.text) ? "0" : pin.text)

但是,如果图钉文本框包含非数字字符串,则将引发错误

一个更安全的解决方案是使用像这样的TryParse方法

int pinNumber = 0;
bool isValidPinNubmer;

isValidPinNubmer = Int32.TryParse(pin.text,out pinNumber)

这将同时验证引脚号并强制转换值,并且在非数字值的情况下,pinNumber变量将为零,希望这会有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM