2015-10-05 21 views
0

在我的情況下,我的網格視圖可以包含普通文本或超鏈接。我想獲得這些領域的價值。到目前爲止,我已經嘗試如何獲取ASP .Net中的網格視圖內的超鏈接字段的文本?

 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循環的第一次迭代之後只有我我得到「指定參數超出有效值的範圍 參數名稱:索引」異常。

任何想法如何解決它?

+0

你可以發佈你的HTML代碼以及GridView嗎? – Nic

回答

0

你可以做到這一點,而不是RowDataBound事件這樣的GridView的: -

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屬性anyways返回一個字符串,因此不需要使用ToString轉換它。

+0

你有機會看到答案嗎?這對你有用嗎? –

相關問題