-1

我不断收到错误“NullReferenceException 未处理。对象引用未设置为对象的实例”在第 5 行

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();

我是编程新手。谢谢

4

3 回答 3

1

Try something like the following. Your connection should noremally be created from your connection. Using statements are a good way of ensuring that classes that implement IDisposable have Dispose called. Use SqlParameters to avoid SQL Injection issues.

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;
   }

}
于 2012-09-14T16:20:03.460 回答
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();
于 2012-09-14T16:34:45.223 回答
-1

能不能在dubug模式下看到查询,看到sql。检查在 sql 中运行相同的查询以查看该帐号是否返回结果。如果没有结果可以避免异常,您可以检查不会引发异常的 DB Null。

于 2012-09-14T16:38:51.100 回答