繁体   English   中英

输入的字符串格式不正确

[英]input string was not in correct format

我有一个在SQL Server 2008中使用asp / C#.net的webforms应用程序。我有一个登录表单,该表单将验证对我的Webform网站的访问。 这是代码。

SqlConnection an = new SqlConnection(@"Data Source=REZRTECH\SQLEXPRESS;Initial Catalog=Temp;Integrated Security=True");
            an.Open();
            SqlCommand anc = new SqlCommand();
            anc.Connection = an;
            anc.CommandText = "Select * From Logins where User_name = @usr";
            anc.Parameters.AddWithValue("@usr", TextBox1.Text);



            int count = Convert.ToInt32(anc.ExecuteScalar());//throws input string was not in correct format exception.
            if (count == 0)
                {
                    string swa = "User Does Not Exist";
                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + swa + "');", true);
                    return;                      
                }
                else
                {
                 //
                    //if user name and password match goto homepage
                    {
                        Response.Redirect("~/Default.aspx");
                    }
                    else
                    {
                        string swa1 = "Invalid Login Credentials";
                        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + swa1 + "');", true);
                    }

我的表行都是nvarchar。 还有另一件事让我感到困惑,一个user_name是admin,其对应的密码也是admin。 假设我输入了除admin以外的任何内容,它成功地给了我用户不存在的错误。 那时“ 不抛出输入字符串异常”

任何和所有帮助表示赞赏。

发生这种情况是因为您使用的是ExecuteScalar设计为仅返回单个值),并且期望该值成为Int32而不是Int32 您的目标似乎是确定用户是否有效。

anc.CommandText = "select cast(count(1) as bit) from Logins where User_name = @usr";

然后,将int count = ...更改为bool isUserValid = (bool)anc.ExecuteScalar()

使用bool代替int count更具描述性和可维护性。 如果您不打算将计数用于某件事,则检索计数是没有用的。

我怀疑你想要得到的总Count的用户的给定UserName 如果要获取Count ,则需要遵循以下SELECT命令语法:

SELECT COUNT(*) from [TableName] WHERE CNDITION;

因此,您在SELECT语句中缺少Count(*)。

替换为:

anc.CommandText = "Select * From Logins where User_name = @usr";

有了这个:

anc.CommandText = "Select count(*) From Logins where User_name = @usr";

暂无
暂无

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

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