在我的情况下,我的网格视图可以包含普通文本或超链接。我想获得这些领域的价值。到目前为止我已经尝试了
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循环的第一次迭代之后我才得到&#34;指定的参数是超出有效值范围。 参数名称:index&#34;异常。
知道怎么解决吗?
答案 0 :(得分:0)
您可以在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
进行转换。