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();
}
Asked
Active
Viewed 132 times
-4

M. Wiśnicki
- 6,094
- 3
- 23
- 28

R Ahmed
- 3
- 3
-
1You 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
-
1Do 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 Answers
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();
}
}
-
-
If it is null it will throw an exception. For avoiding that you can follow this: http://stackoverflow.com/a/20295696/637840 – NicoRiff Dec 29 '16 at 12:30
-
Perhaps handle that possibility in your answer, instead of referencing another link. Also, don't forget `using`. – Zev Spitz Dec 29 '16 at 12:31
-
You could add `top 1` to the query to guarantee a single return result just incase (If UserID isn't the PK of course) – Jon Egerton Dec 29 '16 at 13:49
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