2010-11-28 79 views
1

我運行此,我想以填補文本txtFname數據 - 但它不這樣做沒什麼如何從數據集中填充文本框?

using (Conn = new SqlConnection(Conect)) 
       { 
        Conn.Open(); 

        SQL = "SELECT * FROM MEN where id = '" + txtBAR.Text.Trim() + "'"; 
        dsView = new DataSet(); 
        adp = new SqlDataAdapter(SQL, Conn); 
        adp.Fill(dsView, "MEN"); 
        adp.Dispose(); 
        txtFname.Text = dsView.Tables[0].Rows[3][0].ToString(); 
        txtFname.DataBind(); 
        Conn.Close(); 
       } 

怎麼辦呢?

感謝的提前

+0

也注意到,您的SQL是開放的SQL注入攻擊。你應該總是在你的命令中使用參數。 `select * from men where id = @ id` – 2010-11-28 20:09:40

回答

1
using (Conn = new SqlConnection(Conect)) { 
    try { 
     // Attempt to open data connection 
     Conn.Open(); 

     // Compose SQL query 
     string SQL = string.Format("SELECT * FROM MEN WHERE id = '{0}'", txtBAR.Text.Trim()); 
     using(SqlCommand command = new SqlCommand(SQL,Conn)) { 
      // Execute query and retrieve buffered results, then close connection when reader 
      // is closed 
      using(SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection)) { 
       // Assign txtFname value to search value and clear value if no results returned 
       txtFname.Text = reader.Read() ? reader[0].ToString() : string.Empty; 
       reader.Close(); 
      } 
     } 
    } 
    finally { 
     // Regardless of whether a SQL error occurred, ensure that the data connection closes 
     if (Conn.State != ConnectionState.Closed) { 
      Conn.Close(); 
     } 
    } 
} 

不過,我勸你

  1. 更新您的SQL查詢返回 實際列名稱,而不是*
  2. 更換reader[0].ToString()with reader["FirstName"].ToString()
1
using (Conn = new SqlConnection(Conect)) 
{ 
Conn.Open();  
SQL = "SELECT * FROM MEN where id = '" + txtBAR.Text.Trim() + "'"; 
SqlCommand command= new SqlCommand(SQL,Conn); 
SqlDataReader reader = command.ExecuteReader() 
reader.Read(); 
//Call Read to move to next record returned by SQL 
//OR call --While(reader.Read()) 
txtFname.Text = reader[0].ToString(); 
reader.Close(); 
Conn.Close(); 
} 

編輯:我只注意到「數據集」不是數據庫,反正你正在閱讀的第三行,是你的查詢返回多行嗎?