2010-11-28 76 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(); 
} 

编辑:我只注意到“数据集”不是数据库,反正你正在阅读的第三行,是你的查询返回多行吗?