Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
string equery = "Insert into leave(UserId,leaveType,seasonLeave,Reason)values(@UserId,'" + leavetype.Text.ToString().Trim() + "',@seaonleave,'" + reason.Text.ToString().Trim() + "')";

Where in this query UserId is an foreign key, how i call the @UserId in the C#.
Posted
Updated 21-Aug-13 0:48am
v3

Add parameters to your Command Parameters using:
command.Parameters.AddWithValue(...)

Example Given with your query string:
C#
string equery = "Insert into leave(UserId,leaveType,fromDate,toDate,numdays,seasonLeave,Reason)values(@UserId,'" + leavetype.Text.ToString().Trim() + "',@seaonleave,'" + reason.Text.ToString().Trim() + "')";

SqlConnection connection = new SqlConnection(MyConnectionString);
SqlCommand command = new SqlCommand(equery , connection);

// Adding the value to the parameter "UserID"
command.Parameters.AddWithValue("UserId", txtUserID.Text); 

// Add all your parameters this way ... 


Cheers,
Edo
 
Share this answer
 
v4
Comments
Herbisaurus 21-Aug-13 4:39am    
*****
Adarsh chauhan 21-Aug-13 4:57am    
Nice one.. +5
Joezer BH 21-Aug-13 5:08am    
Thank you Adarsh!
You don't call it - you need to provide it as a parameter. And while you are doing that, do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead throughout.

C#
string equery = "INSERT INTO leave (UserId, leaveType, fromDate, toDate, numdays, seasonLeave, Reason) VALUES(@UserId, @Type, xx, xx, xx, @seaonleave, @Reason)";
using (SqlCommand cmd = new SqlCommand(equery, con))
   {
   cmd.Parameters.AddWithValue("@UserId", myUserId);
   cmd.Parameters.AddWithValue("@Type", leavetype.Text.Trim());
   ... // Continue here with more parameters and so forth
   }
I added the "xx" parts to indicate where you need to specify data that you missed in your original - SQL will complain if you don;t supply sufficient values for the columns you listed.
 
Share this answer
 
Comments
Joezer BH 21-Aug-13 4:41am    
5ed!
Adarsh chauhan 21-Aug-13 4:58am    
Good One.. +5
Gokul Athithan 21-Aug-13 5:01am    
what is tha myUserId
OriginalGriff 21-Aug-13 5:02am    
The value you want to insert in the table...
Gokul Athithan 21-Aug-13 6:01am    
how i want to specify the myUserId in the Program

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