使用gridview检索图像

时间:2012-09-19 07:58:47

标签: asp.net

我想从 OLEDB SQL Server 获取数据并在 gridview 中显示,我能够获取除图像之外的数据:< / p>

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
        AutoGenerateColumns="False" DataSourceID="SqlDataSource1" 
        EnableModelValidation="True" Height="184px" Width="546px">
        <Columns>
            <asp:BoundField DataField="col_FirstName" HeaderText="col_FirstName" 
                SortExpression="col_FirstName" />
            <asp:BoundField DataField="col_LastName" HeaderText="col_LastName" 
                SortExpression="col_LastName" />
            <asp:BoundField DataField="col_age" HeaderText="col_age" 
                SortExpression="col_age" />
            <asp:BoundField DataField="col_photo" HeaderText="col_photo" 
                SortExpression="col_photo" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" 
        SelectCommand="SELECT [col_FirstName], [col_LastName], [col_age], [col_photo] FROM [tbl_PersonInfo_Test]">
    </asp:SqlDataSource>`

2 个答案:

答案 0 :(得分:1)

您可以尝试使用此代码 - 基于asp:ImageField

<asp:ImageField DataImageUrlField="col_photo"></asp:ImageField>

链接:http://msdn.microsoft.com/en-us/library/aa479350.aspx

并替换此代码

<asp:BoundField DataField="col_photo" HeaderText="col_photo" SortExpression="col_photo" />

第二种解决方案 - 基于template field

<asp:TemplateField HeaderText="Status" ItemStyle-HorizontalAlign="Center">
    <ItemTemplate> 
         <asp:Image ID="photo" runat="server" ImageUrl="<%# DataBinder.Eval(Container.DataItem, "col_photo")%>"  />
    </ItemTemplate> 
</asp:TemplateField>

答案 1 :(得分:0)

当您在dataBase中使用 binaryField 时,您可以创建一个简单的imageHandler类。此类知道如何从数据存储加载 图像,并写入 responseStream 即可。请参阅下面的非常粗略的示例

<强> imageHandler.aspx

protected void Page_Load(object sender, EventArgs e)
{
  if (Request.QueryString["ID"] != null)
  {
      int id = Convert.ToInt32(Request.QueryString["ID"]);

      // query your dataStorage for col_photo according to the current id
      // ...

      // access your binaryColumn
     Byte[] bytes = (Byte[])dt.Rows[0]["col_photo"]; // adapt in case you use ExecuteScalar()
     Response.Buffer = true;
     Response.Charset = "";
     Response.Cache.SetCacheability(HttpCacheability.NoCache);
     Response.ContentType = "image/jpeg";
     Response.BinaryWrite(bytes);
     Response.Flush();
     Response.End();
}

<强> ASPX

// don't forget to add the pkColumn to your select statement!!
<asp:ImageField DataImageUrlField="YOUR_PK_COLUMN" 
 DataImageUrlFormatString="imageHandler.aspx?ID={0}"
 ControlStyle-Width="100" ControlStyle-Height="100"/>

您可以在网上找到几个示例。请参阅Displaying Images in gridViewsImagesFromDBinGridView或只询问Mr. Google