c# - 为什么我的代码会显示 System.FormatException:“输入字符串的格式不正确。” 当我将文本框留空并单击提交按钮时?
问题描述
我有一个 ASP.NET 网络表单,它接受用户在 id="pin" 的文本框中输入的数字,并从我的 SQL 数据库中检索插入到其他文本框中的值。一切正常,除了如果我将 pin 文本框留空并单击提交它返回 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)
但是,如果 pin 文本框包含非数字字符串,则会引发错误
更安全的解决方案是像这样使用 TryParse 方法
int pinNumber = 0;
bool isValidPinNubmer;
isValidPinNubmer = Int32.TryParse(pin.text,out pinNumber)
这将验证引脚号并转换值,如果是非数值,则 pinNumber 变量将为零,希望这会有所帮助
推荐阅读
- html - 正确过渡共享边界
- c++ - 如何获取模板类型的内部类型?
- windows - VisualStudio C++ 创建的可执行文件不可部署在其他 Win10 计算机上(错误“0xc000007b”)
- angular - “AbstractControl”类型的参数不能分配给“FormControl”类型的参数
- ruby-on-rails - 修改现有 Rails 应用程序中的路线
- android - Fix warning NullPointerException in android
- c# - 强制执行 REAL 不可为空的字符串引用类型
- javascript - Integer comparison within score board app, score difference equal two
- javascript - Webassembly return c++ uint8_t array and pass that to javascript Uint8Array
- css - CSS 条件选择器 this 或 that