如何从数据集中填充文本框?

时间:2010-11-28 19:38:35

标签: c# asp.net

我运行这个,我想用文本填充文本框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();
                }

怎么做?

提前谢谢

2 个答案:

答案 0 :(得分: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();
}

编辑:我刚注意到'dataSet'不是数据库,无论如何你正在阅读第三行,你的查询是否返回多行?

答案 1 :(得分: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()