Click here to Skip to main content
15,889,335 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am facing this problem.
I want to use the Data entered in a textbox into my query.
i have a textBox where in i am askin the user to enter his name.
now i want to use the data entered by the user in a query like this
Select data from table where username=" the data entered in the TextBox"
i ll be very grateful if someone could help me.
Thanks
Posted

It might help,

I assume your TextBox name is txtUserName then
C#
string queryString= "Select * from Mytable where username='"+ txtUserName.Text +"'";


:)
 
Share this answer
 
Comments
_Zorro_ 28-Jul-11 9:14am    
Actually that's not the right way to build queries, this one is not sql injection proof for example.
C#
string query = string.Format("SELECT data from Table Where UserName = '{0}'", TextBox1.Text);


btw, please keep in my mind that this may lead to SQL Injection. Read more about SQL Injection here:

http://en.wikipedia.org/wiki/SQL_injection
 
Share this answer
 
Build an SQL command, don't concatenate strings. Always use SQL Parameters!


C#
string userName = txtUserName.Text;

SqlCommand cm = new SqlCommand("", YourConnection)
cm.CommandText = "Select FROM YourTable WHERE Name=@UserName"
cm.Parameters.Add("@UserName", SqlDbType.VarChar).Value = userName; 

SqlDataReader reader = cm.ExecuteReader();
if (reader.Read())
{
    // Whatever...
}
 
Share this answer
 
Comments
RaviRanjanKr 28-Jul-11 9:12am    
Nice Answer, 5+
Take that value in a variable
 string Value = TextBox.Text;
SqlConnection Con = new SqlConnection("Your Connection string");
Con.Open();
 SqlCommand Cmd = new SqlCommand("Select * from TableName where UserName = @Value"),Con);
 Cmd.Parameters.addwithvalue("@Value",Value);
 SqlDataAdatpter dt = new SqlDataAdapter(Cmd);
 DataSet ds = new DataSet();
 dt.fill(ds);
Con.Close();
 
Share this answer
 
v2
Comments
parmar_punit 28-Jul-11 10:34am    
nice answer my 5
Mahendra.p25 29-Jul-11 1:36am    
Thanks
C#
SqlCommand command = new SqlCommand("SELECT Field1, Field2, Field3 FROM YourTable WHERE Field4 = @UserName;", connection);

command.Parameters.Add("@UserName", SqlDbType.String).Value = txtUserName.Text;

command.ExecuteNonQuery();

...
...
...
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900