ASP.NET Gridview rowdatabound Stackoverflow异常

时间:2014-05-30 03:46:54

标签: c# asp.net gridview stack-overflow

我从SQL数据源填充了gridview。

每当我打开页面时,我都会在stackoverflow中收到gridview rowdatabound个例外。

导致问题的原因是什么?

Search.aspx

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataSourceID="ConsultsSQLDataSource" ForeColor="#333333" GridLines="None" OnRowDataBound="GridView1_RowDataBound">
     <AlternatingRowStyle BackColor="White" />
     <Columns>
         <asp:BoundField DataField="DATA" HeaderText="Data" SortExpression="DATA" />
         <asp:BoundField DataField="LOCAL" HeaderText="Local" SortExpression="LOCAL" />
         <asp:BoundField DataField="URGENCIA" HeaderText="Urgencia" SortExpression="URGENCIA" />
         <asp:BoundField DataField="ESTADO" HeaderText="Estado" SortExpression="ESTADO" />
         <asp:HyperLinkField HeaderText="Pagamento" NavigateUrl="a" Text="Link" Visible="False" />
         <asp:BoundField DataField="IDPAGAMENTO" SortExpression="IDPAGAMENTO" Visible="False" />
     </Columns>
</asp:GridView>

代码隐藏

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string value = e.Row.Cells[2].Text;
 switch(value)
            {
                case "3":
                    e.Row.Cells[3].Text = "Waiting Payment";
                    HyperLinkField hp = (HyperLinkField)GridView1.Columns[4];
                    GridView1.Columns[4].Visible = true;
                    GridView1.Columns[5].Visible = true;
                    hp.NavigateUrl = "~/Account/Payments/Payment?PaymentID=" + e.Row.Cells[5].Text; //Exception occurs here
                    hp.Text = "Pay";
                    e.Row.Cells[4].Visible = true;
                    break;
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

我注意到如果您通过引用HyperLinkFiled将NavigateUrl和Text分配给超链接(GridView1.Columns [4]),它不会被分配到当前行,而是分配给下一行而不是&# 39;似乎是你所期待的。

重建你的RowDataBound方法:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string value = e.Row.Cells[2].Text;
            switch (value)
            {
                case "3":
                    e.Row.Cells[3].Text = "Waiting Payment";
                    HyperLink hp = e.Row.Cells[4].Controls[0] as HyperLink;
                    hp.NavigateUrl = "~/Account/Payments/Payment?PaymentID=" + e.Row.Cells[5].Text;
                    hp.Text = "Pay";
                    break;
            }
        }
    }

并从HyperLinkField中删除visible="false",并在网格标记中删除最后一个BoundField。

您可以从HyperLinkField中删除Text和NavigateUrl属性,这样只有在链接正确时才能在单元格中显示内容。

尝试一下,看看是否还有错误。