2015-04-06 52 views
0

這是我的代碼轉換gridview到CSV。 Gridview值不是自動生成的列,它從數據庫中作爲templatefield。Gridview單元格文本爲空轉換爲CSV

try 
      { 
       DataTable dt1 = new DataTable(); 
       Response.ClearContent(); 
       Response.AddHeader("content-disposition", "attachment;filename=MyCsvFile.csv"); 
       Response.ContentType = "application/text"; 
       StringBuilder strBr = new StringBuilder(); 
       strBr.Append("\n"); 
       for (int j = 1; j < GridView1.Rows.Count; j++) 
       { 
        strBr.AppendLine(""); 
        for (int k = 0; k < GridView1.HeaderRow.Cells.Count; k++) 
        { 

         strBr.Append(GridView1.Rows[j].Cells[k].Text.Replace(",", "") + ","); 

        } 
        strBr.Append("\n"); 
       } 
       Response.Write(strBr.ToString()); 
       Response.Flush(); 
       Response.End(); 
      } 
      catch (Exception ex) 
      { 
       throw ex; 
      }   

這裏GridView1.Rows [j] .Cells [k] .Text,這個「Text」包含null值。 請幫忙...

+0

請說明問題!發生異常?輸出的格式不符合要求? – 2015-04-06 12:01:28

回答

0

您需要搜索單元內部的控件,因爲列是TemplateField

GridView1.Rows[j].Cells[k].FindControl('ControlId').Text 
+0

謝謝克里斯蒂娜 – user 2015-04-07 04:11:53

+0

對不起..我在我的girdview中使用分頁...但下面的代碼不適用於分頁。請幫助..同時收斂到CSV我在記事本中得到空值。 GridView1.AllowPaging = false; GridView1.DataBind(); – user 2015-04-07 04:30:16

+0

如果要導出所有值,則需要在創建CSV文件時直接從數據庫中獲取它們。以上代碼僅導出網格中的當前頁面。 – 2015-04-07 08:57:40