2

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)?

ycwong
  • 55
  • 6

1 Answers1

3

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());
Abdul Haseeb
  • 514
  • 4
  • 13
  • Which mean I store the session in the user login page, get it at another page?. How can I store it in database by using the insert command? – ycwong Aug 07 '20 at 07:47
  • @ycwong Yes. You can set the session in login page, then retrieve login information from session. Insert command as follows `Insert into table values('"+Session["Username"].ToString()+"')` – Abdul Haseeb Aug 07 '20 at 07:55