无法获取网格视图数据并将其存储到数据库

Can't get the grid view data and store it to database

<div class="container">
    <asp:GridView ID="GridView1" runat="server"  AutoGenerateColumns="False" Font-Size="Medium">

<asp:TemplateField HeaderText="Student ID">
  <ItemTemplate>
     <asp:Label ID="lblID" runat="server"   Width="80px"  Text='<%#Eval("studentID") %>'/>
 </ItemTemplate>


  <asp:TemplateField HeaderText="">
        <ItemTemplate>                                     
                  <asp:LinkButton runat="server"  OnCommand="LinkButton_Click" Text=" VoteCandidate"> </asp:LinkButton>     
         </ItemTemplate>



 </asp:GridView>

    <div>
        <asp:Label ID="Label1" runat="server" ></asp:Label>
    </div>
</div>

这是我用来显示 gridview 的表单。

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


    protected void LinkButton_Click(Object sender, EventArgs e)
    {
        String MyConnection2 = "Server=localhost;database=ovs;Uid=root;password=; Convert Zero Datetime=True";
        foreach (GridViewRow g1 in GridView1.Rows)
        {
            MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
            
            String query = "insert into voting (studentID)values ('" + g1.Cells[0].Text + "')" ;
            MySqlCommand MyCommand2 = new MySqlCommand(query, MyConn2);
         
          MySqlDataReader MyReader2;
          MyConn2.Open();
          MyReader2 = MyCommand2.ExecuteReader();
          MyConn2.Close();
        }

    }

当我执行sql插入命令时,没有发生错误,但我希望gridview中显示的学生ID存储在投票table中,但投票table 为空。

由于您在 GridView 中使用了模板字段,因此您不能直接使用单元格,您需要像这样在单元格内查找标签:

foreach (GridViewRow g1 in GridView1.Rows)
{
    Label lblStudentId = (Label)g1.Cells[0].FindControl("lblID");
    string studentId = lblStudentId.Text;
    // now proceed with your inserting.
}

但是,如果您按照现在的方式使用循环,GridView 中的每一行都会有一个插入,而不仅仅是您单击的行...
如果要获取 LinkButton 所在行的 ID,请不要遍历这些行。而是像这样使用发件人的 NamingContainer-属性:

LinkButton linkButton = (LinkButton)sender;
GridViewRow g1 = (GridViewRow)linkButton.NamingContainer;
Label lblStudentId = (Label)g1.Cells[0].FindControl("lblID");
string studentId = lblStudentId.Text;
// now proceed with your inserting.

有关详细信息,请参阅 this question and answer