2011-06-16 71 views
-3
private void TxtFarmerCode_TextChanged(object sender, EventArgs e) 
     { 
      try 
      { 
       cmd.Open(); 
       cmd = new SqlCommand("Select farmername, from cottonpurchase where [email protected]", conn); 
       cmd.Parameters.Add("@aa", SqlDbType.Int).Value = TxtFarmerCode.Text; 
       dr = cmd.ExecuteReader(); 
       if (dr.HasRows == false) 
       { 
        throw new Exception(); 
       } 
       if (dr.Read()) 
       { 
        // textBox1.Text = dr[0].ToString(); Since U r going to give the ID and retrieve in textBox1. 
        TxtFarmerName.Text = dr[0].ToString(); 
        //textBox3.Text = dr[1].ToString(); 
        //textBox4.Text = dr[2].ToString(); 
        //textBox7.Text = dr[3].ToString(); 
        //dateTimePicker1.Text = dr[4].ToString(); 
        //dateTimePicker2.Text = dr[5].ToString(); 
        //textBox5.Text = dr[6].ToString(); 
       } 
      } 
      catch 
      { 
      // lblError = "THE GIVEN ID IS UNAVAILABLE"; 
      } 
      finally 
      { 
       conn.Close(); 
      } 
+1

請顯示實際的錯誤。 – 2011-06-16 16:10:15

+0

你是否從某處複製代碼?看來博士,康恩和CMD沒有宣佈。 – marto 2011-06-16 16:21:03

+2

我認爲這是來自[本文發表](http://www.daniweb.com/software-development/csharp/threads/95937/1090530#post1090530) – 2011-06-16 16:27:47

回答

0

你缺少連接塊的一些錯誤(不管你要連接到更換connectionString):

using (SqlConnection conn= new SqlConnection(
      connectionString)) 
    { 
     //You have cmd.Open it should be connection 
     conn.Open(); 
     cmd = new SqlCommand("Select farmername, from cottonpurchase where [email protected]", conn); 
     cmd.Parameters.Add("@aa", SqlDbType.Int).Value = TxtFarmerCode.Text; 
     dr = cmd.ExecuteReader(); 
     if (dr.HasRows == false) 
     { 
      throw new Exception(); 
     } 
     if (dr.Read()) 
     { 
     // textBox1.Text = dr[0].ToString(); Since U r going to give the ID and retrieve in textBox1. 
     TxtFarmerName.Text = dr[0].ToString(); 
     //textBox3.Text = dr[1].ToString(); 
     //textBox4.Text = dr[2].ToString(); 
     //textBox7.Text = dr[3].ToString(); 
     //dateTimePicker1.Text = dr[4].ToString(); 
     //dateTimePicker2.Text = dr[5].ToString(); 
     //textBox5.Text = dr[6].ToString(); 
     } 
    } 
    catch 
    { 
     // lblError = "THE GIVEN ID IS UNAVAILABLE"; 
    } 
    finally 
    { 
     conn.Close(); 
    } 
    } 

邊注... NEVERcatch {}

+0

我不明白?我想從我的數據庫中提取值,請你幫我解決嗎? – tanya 2011-06-16 16:08:07

+0

它仍然給我錯誤 – tanya 2011-06-16 16:09:08

+0

首先cmd沒有打開,所以我很確定你需要使用上面的語句。 – Nix 2011-06-16 16:12:37