如何在文本框中显示数据库值

时间:2016-12-29 11:57:03

标签: c# sql-server-2008

void GetUsername(string Username)
{ 
  SqlConnection con = new SqlConnection("Data Source=METHOUN-PC;Initial Catalog=ITReportDb;Integrated Security=True");
  SqlCommand cmd = new SqlCommand("Select UserName from tblLogin where UserId='" + Username + "'", con);
  con.Open();
  SqlDataReader rdr = cmd.ExecuteReader();
  if (rdr.Read())
   {
    TextBox1.Text = rdr.GetValue(0).ToString();
   }
   rdr.Close();
   con.Close();
}

2 个答案:

答案 0 :(得分:0)

如果您确定查询只返回一个值,则可以使用ExecuteScalar方法。

void GetUsername(string Username)
{
    var sql = @"
        SELECT UserName
        FROM tblLogin
        WHERE UserId = @Username
    ";
    var connectionString = @"
        Data Source=METHOUN-PC;
        Initial Catalog=ITReportDb;
        Integrated Security=True
    ";

    using (var con = new SqlConnection(connectionString)) {
        con.Open();
        var cmd = con.CreateCommand();
        cmd.CommandText = sql;
        cmd.Parameters.AddWithValue("@Username", Username);
        TextBox1.Text = cmd.ExecuteScalar()?.ToString();
        con.Close();
    }
}

答案 1 :(得分:0)

textBox.Text = GetUsername(userID);

string GetUsername(string userID) {
    var resultTable = new DataTable();
    var connection = new SqlConnection("Data Source=METHOUN-PC;Initial Catalog=ITReportDb;Integrated Security=True");
    con.Open();
    var command = new SqlCommand("SELECT Username FROM tblLogin WHERE UserId='" + userID + "';", connection);
    var adapter = new SqlDataAdapter(command);
    adapter.Fill(resultTable);
    con.Close();
    return resultTable.Rows[0]["Username"].ToString();
}

我个人会使用上述方法。如果您决定显示多个用户名,那么使用SqlDataAdapter类将来会有所帮助,因此它不仅限于一个。