0
 protected void LinkButton_Click(Object sender, EventArgs e)
    {
        String MyConnection2 = "Server=localhost;database=ovs;Uid=root;password=; Convert Zero Datetime=True";
        DateTime time = DateTime.Now;              // Use current time
        string format = "yyyy-MM-dd HH:mm:ss";
        string UserName4 = HttpContext.Current.User.Identity.Name;
        GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
        Label lblStudentId = (Label)grdrow.Cells[0].FindControl("lblID");
        string studentId = lblStudentId.Text;
        String query = "insert into voting (CandidateStudentID,voterStudentID,DateTime)values ('" + lblStudentId.Text + "','" + Session["UserName"].ToString() + "','" + time.ToString(format) + "')";
        foreach (GridViewRow row in GridView2.Rows)
        {
            Label lblVoter = row.FindControl("lblVoter") as Label;
            string voterID = lblVoter.Text;


            if (Session["UserName"].ToString().Equals(lblVoter.Text))
            {
                Label1.Text = "You voted before";

            }

        }
        MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
        MySqlCommand MyCommand2 = new MySqlCommand(query, MyConn2);
        MySqlDataReader MyReader2;
        MyConn2.Open();
        MyReader2 = MyCommand2.ExecuteReader();
        Label2.Text = "Thank you for You Vote";

    }


  <asp:GridView ID="GridView2" runat="server"  AutoGenerateColumns="False" Font-Size="Medium">
          <Columns>
          <asp:TemplateField HeaderText="Student ID">
  <ItemTemplate>
     <asp:Label ID="lblVoter" runat="server"   Width="150px"  Text='<%#Eval("voterStudentID") %>'/>
 </ItemTemplate>
 </asp:TemplateField>
              
          </Columns>
       </asp:GridView>


 protected void loadCandidate()
    {
        con.Open();
        MySqlCommand cmd = new MySqlCommand("select studentID ,name from candidate  ", con);
        MySqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows == true)
        {
            GridView1.DataSource = dr;
            GridView1.DataBind();
            con.Close();

            con.Open();
            MySqlCommand cmd2 = new MySqlCommand("select voterStudentID from voting  ", con);
            MySqlDataReader dr2 = cmd2.ExecuteReader();

            GridView2.DataSource = dr2;
            GridView2.DataBind();
        }
    }

StudentID display in gridview2

I want to prevent duplicate voting in the database. Now I'm facing a problem which when the user login as first users in the StudentID table which is 1909404, when the 1909404 already exist in the database, It will display the error message. But when the user's login as the second user in the StudentID table which is 1909362, even though the user ID already exists, It will no show the error message. I would like to show the error message as long as the user ID existed in the database (which mean they voted before).

Kekw Yc
  • 5
  • 4
  • How is `GridView2` getting its data and how often is it updated? – JohnG Oct 20 '20 at 04:32
  • Hello, I had updated my code on how gridview2 gets the data. The gridview2 will be updated every time when there is a user click the vote button. – Kekw Yc Oct 20 '20 at 04:48
  • Well… it seems clear the problem is on the line… `if (Session["UserName"].ToString().Equals(lblID.Text)) …` , have you put a break point there and examined the values? In other words, IF the ID IS in `GridView2`, THEN… is it also the current `Session[“UserName”]`? Obviously if they are the same and it is not setting the label “You Voted before”… then something else is going on. Can verify that when the values are the same that it drops to the `else` portion of the `if` statement? OR is `label1.Text` possibly getting set to something else after this code? – JohnG Oct 20 '20 at 05:01
  • When the user login as 1909404, then the Session["UserName"] will now store 1909404, when it 1909404 try to vote for a second time, the error message "you voted before" will be shown. But for the user 1909362, the error message won't show even though the uses already voted. I wonder why it works with the 1909404 but not the 1909362. Is it because of Label lblID = (Label)GridView2.Rows[0].FindControl("lblVoter"); ? – Kekw Yc Oct 20 '20 at 05:08
  • Have you checked the values as I described previously? It may work for 1909404, because the values are the same. In MAY not work for 1909362, because the values are NOT the same. You do not appear to be verifying this other than the final result. Put a break point as described previously and CHECK the values. – JohnG Oct 20 '20 at 05:12
  • Sorry for not reply to you when you ask me to check the value. I had put the breakpoint to examine it. When the user login as 1909362, the value in the "label1.Text" is still 1909404, that why it won't show the error message. – Kekw Yc Oct 20 '20 at 05:19
  • Sounds like you got it. And that sounds about right, you would need to loop through ALL the rows in `GridView2` to determine if the current user is in the grid. – JohnG Oct 20 '20 at 05:26
  • As I said in my last comment… you need to loop through ALL the rows in `GridView2` to determine if `Session[“UserName”]` is equal to one of the rows in the grid. Currently the code is ONLY looking at the first row… `Label lblID = (Label)GridView2.Rows[0].FindControl("lblVoter");` That is why the numbers do not match on the second number. Your code needs to loop through ALL the rows and if it is NOT found, then they can vote. Obviously if the name IS found, then you can quit the loop and post the “you voted message.” – JohnG Oct 20 '20 at 05:34
  • Your update wont work as expected. In the `foreach` loop… You only want to check if the ID’s equals one of the IDs in `GridView2` IF a match is found, simply post the you voted message and return… nothing more is needed. However, if you exit the `foreach` loop and the code has NOT returned… then they can vote. Ie… `foreach (row in grid2) if (names are equal) then post can’t vote message and exit`… No `else` statement is needed and end the for each loop. If you “EXIT” the `foreach` loop then that means the name was NOT found… then they can vote. – JohnG Oct 20 '20 at 05:55
  • Which means I do not need to put the else statement right? May I know where should I put the command to execute the insert query and the successful message? I tried to remove the else statement and put the insert query and the successful message outside of foreach, it also show the same error, which display an error and successful message at the same time and insert the duplicate studentID into database – Kekw Yc Oct 20 '20 at 06:02

1 Answers1

1

Change it like this....

foreach (GridViewRow row in GridView2.Rows) {
  Label lblVoter = row.FindControl("lblVoter") as Label;
  if (Session["UserName"].ToString().Equals(lblVoter.Text)) {
    Label1.Text = "You voted before";
    return;
  }
}
// Since we looped through all the rows and did NOT find a match...
// Then they can vote 
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
Label2.Text = "Thank you for You Vote";
JohnG
  • 9,259
  • 2
  • 20
  • 29
  • OMG! It's Work! Thank you so much so spending your time guiding me and teach me how to solve the error. I really appreciate it! – Kekw Yc Oct 20 '20 at 06:15
  • @Kekw Yc ... Glad you got it working. One last point you should address, in the query string, you should ALWAYS parameterize your queries. Even though you are using a `Label` in the query… `lblStudentId.Text`, it is WISE to get in the habit of parametrizing just about anything from the “outside” world that is used as a string in a query. – JohnG Oct 20 '20 at 06:20
  • Noted with thanks! Will try to improve the current code with your suggestion! – Kekw Yc Oct 20 '20 at 06:27