如何在网格视图中获取超链接字段的文本

本文关键字:超链接 字段 文本 获取 网格 视图 | 更新日期: 2023-09-27 18:16:05

在我的例子中,我的网格视图可以包含普通文本或超链接。我想要得到这些字段的值。到目前为止,我已经尝试了

        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" exception.

有什么好办法吗?

如何在网格视图中获取超链接字段的文本

您可以在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);
        }
    }
}

你可以像这样把这个事件附加到gridview上:-

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

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