簡體   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