2010-06-23 64 views
0

我有一個datagridview並綁定一個包含簡單文本而不是圖像的blob字段的表。在此datagridview嘗試顯示文本爲圖像並生成一個異常。 是否可以禁用datagridview顯示與blob字段對應的圖像?DataGridView圖像禁用

的代碼大約是這樣的:

// maybe datagridview has some property to set in order to disable such behavior? 
gridView.DataSource = mytable_with_blob_field; 

回答

0

您可以設置AutoGenerateColumns爲false,並手動添加非BLOB字段。

<asp:BoundField HeaderText="Header text" DataField="FieldToBind" /> 

對於blob列,改爲添加TemplateField

<asp:TemplateField HeaderText="Blob as Text"> 
    <ItemTemplate> 
     <asp:Literal ID="blob" runat="server" Text='<%# new UTF8Encoding().GetString((Container.DataItem as Custom).Blob) %>' /> 
    </ItemTemplate> 
</asp:TemplateField> 

所得弄成這個樣子:

<asp:GridView ID="grid" runat="server" AutoGenerateColumns="false"> 
    <Columns> 
     <asp:BoundField HeaderText="Header text" DataField="FieldToBind" /> 
     <asp:TemplateField HeaderText="Blob as Text"> 
      <ItemTemplate> 
       <asp:Literal ID="blob" runat="server" Text='<%# new UTF8Encoding().GetString((Container.DataItem as Custom).Blob) %>' /> 
      </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

這裏是從服務器端的完整的測試代碼:

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Web.UI.WebControls; 

namespace TestWeb 
{ 
    public class Custom 
    { 
     public string FieldToBind { get; set; } // other fields 
     public byte[] Blob { get; set; } // your blob 
    } 

    public partial class _Default : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      var list = new List<Custom>(); 
      list.Add(new Custom { FieldToBind = "pure text", Blob = new UTF8Encoding().GetBytes("blob") }); 
      grid.DataSource = list; 
      /*grid.RowDataBound += (rS, rE) => 
      { 
       if (rE.Row.RowType == DataControlRowType.DataRow) 
       { 
        // could also be bound by the server-side 
        //(rE.Row.FindControl("blob") as ITextControl).Text = new UTF8Encoding().GetString((rE.Row.DataItem as Custom).Blob); 
       } 
      };*/ 
      grid.DataBind(); 
     } 
    } 
}