【问题标题】:How to get the text of a hyperlink field inside a grid view in ASP .Net?如何在 ASP .Net 中的 gridview 中获取超链接字段的文本?
【发布时间】:2015-10-05 07:57:42
【问题描述】:

在我的情况下,我的网格视图可以包含普通文本或超链接。我想获得这些字段的值。到目前为止,我已经尝试过

        DataTable detailTable = new DataTable();
        for (int i = 0; i < gvTransactionDetails.Columns.Count; i++)
        {
            detailTable.Columns.Add(gvTransactionDetails.HeaderRow.Cells[i].Text.ToString());
        }

        foreach (GridViewRow gvrow in gvTransactionDetails.Rows)
        {
            DataRow dr = detailTable.NewRow();
            for (int j = 0; j < gvTransactionDetails.Columns.Count; j++)
            {
                Control hyperLink = gvrow.Cells[j].Controls[0] as LiteralControl;

                if (hyperLink != null)
                {
                    dr[j] = ((LiteralControl)gvrow.Cells[j].Controls[0]).Text.ToString();
                }
                else
                {
                    dr[j] = gvrow.Cells[j].Text.ToString();
                }
            }

            detailTable.Rows.Add(dr);
        }

我面临的问题是,每一行中的第一个单元格是一个超链接,其余所有单元格只包含文本值,只有在 foreach 循环的第一次迭代之后,我才得到“指定的参数超出了有效值的范围。 参数名称:index”异常。

知道如何解决吗?

【问题讨论】:

  • 你可以为 GridView 发布你的 HTML 代码吗?

标签: c# asp.net hyperlink


【解决方案1】:

您可以在 gridview 的RowDataBound 事件中执行此操作,如下所示:-

protected void gvTransactionDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        LinkButton lnkId= (LinkButton)e.Row.FindControl("lnkId");
        if (lnkId!= null)
        {
            detailTable.Rows.Add(lnkId.Text);
        }
    }
}

您可以像这样将此事件附加到您的网格视图:-

<asp:GridView ID="gvTransactionDetails" runat="server" 
              OnRowDataBound="gvTransactionDetails_RowDataBound">

另外,作为您发布代码的旁注,.Text.ToString(); Text 属性无论如何都会返回一个字符串,因此无需使用ToString 对其进行转换。

【讨论】:

  • 你有机会看看答案吗?这对你有用吗?
猜你喜欢
  • 1970-01-01
  • 2013-08-11
  • 2013-08-13
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-26
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多