2014-04-01 58 views
0

我使用ASP.net和C#創建網站註冊表單。我在家中創建了一個小型的sqlcommand [不同的計算機]來選擇表中的用戶名,並將它們與給定的用戶名進行匹配,但是我得到一個錯誤。System.NullReferenceException錯誤

Error123: System.NullReferenceException: Object reference not set to an instance of an object. at index.Page_Load(Object sender, EventArgs e) in e:\Year 2\Internet App Development\Assignment 2\assignment 2\account.aspx.cs:line 18Error: System.NullReferenceException: Object reference not set to an instance of an object. at index.submitButton_Click(Object sender, EventArgs e) in e:\Year 2\Internet App Development\Assignment 2\assignment 2\account.aspx.cs:line 41

代碼中的錯誤:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (IsPostBack) 
    { 
     try 
     { 
      SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString); 
      connection.Open(); 
      string checkuser = "select count(*) from userTable where Username='" + userValBox.Text + "'"; 
      SqlCommand com = new SqlCommand(checkuser, connection); 
      int temp = Convert.ToInt32(com.ExecuteScalar().ToString()); 
      if (temp == 1) 
      { 
       Response.Write("Username already exists"); 
      } 

      connection.Close(); 
     } 
     catch(Exception ex) 
     { 
      Response.Write("Error123: " + ex.ToString()); 
     } 
    } 
} 

對不起,這是一個重複的問題,我已經通過其他人搜索和所遇到什麼。提前致謝!

+0

空值,如果存在(的IsPostBack)如果通過,並嘗試更換(的IsPostBack!)。 – sk7730

+1

'Convert.ToInt32(com.ExecuteScalar());'應該解決我想的問題 –

+0

哪一行出錯?什麼是'userValBox'變量? – idlerboris

回答

0

連接字符串的名稱與您的web.config中的連接字符串不匹配。

更改此:

ConfigurationManager.ConnectionStrings["RegistrationConnectionString"] 

要:

ConfigurationManager.ConnectionStrings["ConnectionString"] 

此外,你應該改變這一點,因爲它可能會走壞:

com.ExecuteScalar().ToString() 

你應該試試這個:

obj result = com.ExecuteScalar(); 

if (result != null) 
{ 
    int count = Convert.ToInt32(result); 
} 

或者乾脆:

int count = Convert.ToInt32(com.ExecuteScalar()); 
+0

'Convert.ToInt32(com.ExecuteScalar());'就足夠了,不需要空檢查 –

+0

我已經輸入了一條記錄到那個數據庫表中並且使用用戶名來檢查。無論我使用什麼,我都會得到同樣的錯誤。我試過你的方法,但沒有成功 – horHAY

+0

我認爲它應該是'ConfigurationManager.ConnectionStrings [「ConnectionString」]':) – Nilesh

0

原因 「System.NullReferenceException」 有沒有可能是com.executescalar

+0

那個已經被覆蓋了。 –

相關問題