2012-09-14 35 views
-1

我不斷收到錯誤「的NullReferenceException是未處理的,未將對象引用設置到對象的實例」上線5的ExecuteScalar錯誤

1. Private void textbox1_TextChanged(object sender,EventArgs e) 
2  { 
3.  SqlConnection cn=new SqlConnection("Connection string"); 
4.  String sql ="select name from bank_info where account_no ='"+textbox1.Text+"'"; 
5.  SqlCommand cmd =new SqlCommand(sql,cn); 
6.  Cn.Open(); 
7.  String s1 = cmd.ExecuteScalar().ToString(); 
8.  TextBox2.Text =s1.ToString(); 

是新來programming.Thanks

+0

該錯誤「NullReferenceException未處理」。甚至沒有接近你在該代碼中的唯一錯誤 –

+0

還有什麼其他錯誤? – user1568350

+1

你明白人們輸入的速度非常快,並且你每次在文本框中改變文本時都試圖建立一個連接到數據庫 - 對於其他錯誤,來自@Mr Moose的答案修復了這些修復了大多數錯誤的 –

回答

1

嘗試類似如下。你的連接應該從你的連接創建。使用語句是確保實現IDisposable的類具有Dispose調用的好方法。使用SqlParameters來避免SQL注入問題。

using(SqlConnection cn=new SqlConnection("Connection string")) 
{ 
    cn.Open(); 

    String sql ="select name from bank_info where account_no = @accNo"; // '"+textbox1.Text+"'"; 

    using (SqlCommand cmd = cn.CreateCommand()) 
    { 
     cmd.CommandText = sql; 
     SqlParameter param = cmd.CreateParameter(); 
     param.ParameterName = "@accNo"; 
     param.Value = textbox1.Text; 
     cmd.Parameters.Add(param); 
     object obj = cmd.ExecuteScalar(); 
     TextBox2.Text = obj != null ? obj.ToString() : string.Empty; 
    } 

} 
+0

代碼中的問題,除了他詢問的nullreferenceexception(如果executecalar返回null,仍然會發生) –

+0

您是對的。我的意思是解決這個問題。 –

+0

@Mr Moose-Am得到錯誤(名稱'cn'在當前上下文中不存在),cn.open()和cn.createcommand用藍色波浪線加下劃線 – user1568350

0

這將有助於

Private void textbox1_TextChanged(object sender,EventArgs e) 
{ 
    SqlConnection cn=new SqlConnection("Connection string"); 
    String sql ="select name from bank_info where account_no ='"+textbox1.Text+"'"; 
    SqlCommand cmd =new SqlCommand(sql,cn); 
    Cn.Open(); 
    Object obj = cmd.ExecuteScalar() 
    String s1 = (obj!=null)?(String)obj:""; 
    TextBox2.Text =s1.ToString(); 
+0

非常感謝...我是一名救生員 – user1568350

-1

,你可以看到在dubug方式查詢並請參閱SQL。檢查在SQL中運行相同的查詢來查看該帳號是否返回結果。如果沒有結果 以避免異常,則可以檢查不會拋出異常的DB Null。