【问题标题】:Can't get the grid view data and store it to database无法获取网格视图数据并将其存储到数据库
【发布时间】:2020-08-05 04:44:59
【问题描述】:
<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>

这是我显示网格视图的表单。

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 insert命令时,没有出现错误,但我希望gridview中显示的studentID存储在投票表中,但投票表上的studentID是空的。

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    由于您在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-property:

    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

    【讨论】:

    • 您好,您能给我一些建议吗?如何在网格视图中插入我选择的行而不是每一行?
    • 更新答案 - 看看
    猜你喜欢
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多