How to get the username when they login and store it to database

I want to get the username when users login, after that, when they want do vote for a particular candidate, they click the vote button, then the users’s username will be store in the database. Any suggestion on how to do it? For the display of the candidate details(for voting), i use the gridview, now, I able to store the candidate details in the database, just left the username of the voter.

protected void LinkButton_Click(Object sender, EventArgs e)
    {
        String MyConnection2 = "Server=localhost;database=ovs;Uid=root;password=; Convert Zero Datetime=True";
     
        MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);      
        GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
        Label lblStudentId = (Label)grdrow.Cells[0].FindControl("lblID");
        string studentId = lblStudentId.Text;
        String query = "insert into voting (studentID,)values ('" + lblStudentId.Text + "')";  
        MySqlCommand MyCommand2 = new MySqlCommand(query, MyConn2);
        MySqlDataReader MyReader2;
        MyConn2.Open();
        MyReader2 = MyCommand2.ExecuteReader();

        while (MyReader2.Read())
        {
        }
        MyConn2.Close();
    }

    }

When the users click the vote button, the candidateID that being displayed in the gridview will be store to the database.However, I want to store who vote for the particular candidate (store they studentID). I’d like capture thier username when they login, and when they click the vote button, insert their studentID to the database

 Session["UserName"] = txtID.Text;
txtID.Text = Session["UserName"].ToString();

I store the session in the user login page. How can I store it to the database using the insert command(when they click the vote button)?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use Viewstate or Session object to store the username. Then retrieve the username from that.
Set value to session or viewstate

Session["Username"]=txtusername.Text;
Viewstate["Username"]=txtusername.Text;

get value from session or viewstate

Response.Write(Session["Username"].ToString());
Response.Write(Session["Username"].ToString());


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x