-4
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();
}
M. Wiśnicki
  • 6,094
  • 3
  • 23
  • 28
R Ahmed
  • 3
  • 3
  • 1
    You have to explain what you want to accomplish, and what you have done. You don´t have to post code alone, and please format as such – NicoRiff Dec 29 '16 at 12:00
  • 1
    Do you realy want to get user name by user name? – gabba Dec 29 '16 at 12:04
  • 1
    [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection – marc_s Dec 29 '16 at 12:26

2 Answers2

0

if you are sure that the query will return only one value you can use the ExecuteScalar method.

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();
    }
}
Zev Spitz
  • 13,950
  • 6
  • 64
  • 136
NicoRiff
  • 4,803
  • 3
  • 25
  • 54
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();
}

I would personally use the above method. Using the SqlDataAdapter class will help in future if you decide to display multiple usernames so it's not limited to one.

Nathangrad
  • 1,426
  • 10
  • 25