如何使用vb.net从数据库中检索二进制图像并将图像插入到GridView中。
这是我的数据库
image(id为整数,img为varbinary(max))
答案 0 :(得分:0)
在澄清您所指的gridview的类型时,以下是如何在数据库中插入数据:
Using c As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
c.Open()
Dim command = New SqlCommand("INSERT INTO yourtable(image) values (@image)", c)
' this is specific to the FileUploadControl but the idea is to get the
'image in a byte array; however you do it, it doesn't matter
Dim buffer(FileUpload1.PostedFile.ContentLength) As Byte
FileUpload1.PostedFile.InputStream.Read(buffer, 0, buffer.Length)
command.Parameters.AddWithValue("@image", buffer)
command.ExecuteNonQuery()
End Using
假设您正在讨论ASP .NET应用程序,可以按如下方式将数据绑定到gridview:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<!--Trick to encode the bytes as a BASE64 string-->
<img width="100px" height="100px" src='data:image/png;base64,<%#System.Convert.ToBase64String(Eval("image"))%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=Your_ConnectionString_GoesHere"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [id], [image] FROM [your_table_name_goes_here]">
</asp:SqlDataSource>