获取GridView DataKeyName并在外部按钮中使用

时间:2018-06-30 11:59:52

标签: c# asp.net visual-studio gridview webforms

我正在使用ASP.NET Web应用程序(.NET Framework)。

我有一个带有自动生成的“选择”按钮的GridView和一个位于GridView外部的“批准”按钮。我想单击“选择”链接以获取DataKeyName(ViewingRequestID),并在“批准”按钮的onClick方法中使用它。

运行代码时,单击“选择”,它会提供正确的ViewingRequestID。但是当我单击“批准”之后,ViewingRequestID变为0。

如何获得保持不变的价值?

HTML

<asp:GridView ID="gvViewingRequests" runat="server" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Horizontal" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="ViewingRequestID" PageSize="5" OnRowCommand="gvViewingRequests_RowCommand" AutoGenerateSelectButton="True">
                    <AlternatingRowStyle BackColor="#F7F7F7" />
                    <Columns>
                        <asp:BoundField DataField="ViewingRequestID" HeaderText="Viewing Request ID" />
                        <asp:BoundField DataField="ParentID" HeaderText="Parent ID" />
                        <asp:BoundField DataField="StudentName" HeaderText="Student Name" />
                        <asp:BoundField DataField="StudentID" HeaderText="Student ID" />
                        <asp:BoundField DataField="Status" HeaderText="Status" />
                        <asp:BoundField DataField="DateCreated" HeaderText="Date Created" />
                    </Columns>
                    <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
                    <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
                    <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Center" />
                    <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
                    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
                    <SortedAscendingCellStyle BackColor="#F4F4FD" />
                    <SortedAscendingHeaderStyle BackColor="#5A4C9D" />
                    <SortedDescendingCellStyle BackColor="#D8D8F0" />
                    <SortedDescendingHeaderStyle BackColor="#3E3277" />
</asp:GridView>

隐藏代码

ViewingRequest viewingRequest = new ViewingRequest();

    protected void gvViewingRequests_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int i = Convert.ToInt32(e.CommandArgument);

        viewingRequest.viewingRequestID = Convert.ToInt32(gvViewingRequests.Rows[i].Cells[1].Text);  
    }

    protected void btnApprove_Click(object sender, EventArgs e)
    {


        int errorCode = viewingRequest.changeStatus(viewingRequest.viewingRequestID, "A");

        if (errorCode == 0)
        {
            displayViewingRequests();
            lblMsg.Text = $"Viewing Request {viewingRequest.viewingRequestID} approved.";
        }
    }        

0 个答案:

没有答案