I’m using ASP.Net/C# and I have a form that allows people to add information into a table and along with it I want to collect the Current Users GUID and insert it.
I have a field setup (UserID) as a unique identifier and I have the following code:
protected void Page_Load(object sender, EventArgs e)
{
MembershipUser currentUser = Membership.GetUser();
Guid temp = (Guid)(Membership.GetUser(User.Identity.Name).ProviderUserKey);
Guid @currentUserID = temp;
}
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\ASPNETDB.MDF;Integrated Security=True;User Instance=True");
SqlCommand cmd;
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("insert into Accom (UserID) values('" + @currentUserID + "')", con);
cmd.ExecuteNonQuery();
}
I basically want to link the variable to the Database any idea how as the above gives errors.
You are defining a variable
currentUserIDin local scope – you must save this variable in theSessionso you can access it in theButton1_Clickmethod:Now you can retrieve it in
Button1_Click:Also the @ is not needed nor should it be there, you only should need it if you want to define variables with a name that matches a C# keyword – this is bad style anyway. Also you want to put the
SqlConnectionspecific code all within the button click handler – otherwise this variable is instantiated evertime the page loads, not just when the button click handler is used. Finally you also want to useSqlParametersinstead of strings in your SQL insert statement.Edit:
As @pst pointed out, the more “ASP.NET way” would be to just use an instance variable
that you declare as part of the class, not within a method – then you can use this variable throughout the page. This means however, the user id will not be available on other pages (with a session it could be retrieved through the life time of the session on any page).