I have a grid view in a web application in visual studio with a sql query attached to it. How do i pass the Username the person has logged in with into a parameter in the query
-
are you trying to update the database with a username or put new records into the database with the username?Dustin– Dustin2016-03-31 22:07:55 +00:00Commented Mar 31, 2016 at 22:07
-
i am trying to pull data from a table where the parameter is the name they have logged in with. So e.g select * from contact where name = @LoginNameBazF11982– BazF119822016-04-01 10:55:08 +00:00Commented Apr 1, 2016 at 10:55
-
If you are looking for the Windows username, I use C# to grab the username. I've shown this below in an answer.Dustin– Dustin2016-04-01 11:24:45 +00:00Commented Apr 1, 2016 at 11:24
-
I just edited it to include how to find SQL-Server user_nameDustin– Dustin2016-04-01 11:32:51 +00:00Commented Apr 1, 2016 at 11:32
-
If a user logs into a website how would i pull that username they logged into a website with in a scriptBazF11982– BazF119822016-04-04 08:40:12 +00:00Commented Apr 4, 2016 at 8:40
|
Show 2 more comments
2 Answers
You need to insert the user's input as a variable into the SQL Query using command.Parameters.AddWithValue(). Quick Example..
var command = new SqlCommand("INSERT INTO Users (Username) VALUES (@Username)");
command.Parameters.AddWithValue("@Username", txtUsername.Text);
command.ExecuteNonQuery();
Comments
You get the username the user is logged in with (in Windows) by executing:
String userName = Environment.UserName;
In your SQL query, you would use this variable like this:
String SQLQuery = "SELECT * FROM [YourTable] WHERE colUserName = '" + userName + "';";
If you are looking for the username the person is logged into SQL-Server with (for example) you would use:
SELECT system_user;
to get:
String SQLQuery = "SELECT * FROM [YourTable] WHERE colUserName = system_user;";