I am currently trying to display the a QR code bitmap image that is being stored as varbinary in the SQL database into a gridview, and I have referred to this link: [https://www.aspsnippets.com/Articles/Display-images-from-SQL-Server-Database-in-ASP.Net-GridView-control.aspx]
However, I am unable to display the image properly in the gridview table and I couldn't seem to figure out the error with it.
This is my code for the gridview code behind:
if (!this.IsPostBack)
{
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM PARCEL", conn))
{
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView dr = (DataRowView)e.Row.DataItem;
string imageUrl = "data:image/png;base64," + Convert.ToBase64String((byte[])dr["QRCode"]);
(e.Row.FindControl("QRCode") as Image).ImageUrl = imageUrl;
}
}
The markup for gridview:
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="ConsignmentNumber"
AllowPaging="True"
HorizontalAlign="Center"
ViewStateMode="Enabled">
<Columns>
<asp:BoundField DataField="ConsignmentNumber" HeaderText="ConsignmentNumber" ReadOnly="True" SortExpression="ConsignmentNumber" />
<asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="QRCode" runat="server" HeaderText="QRCode" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I would like to know if there is any solution or suggestion that I can apply in order to display the images properly.
Judging by the error you are experiencing, you have defined a DataSourceId
in your markup AND are setting the datasource in codebehind. You can do either, but not both. That is what the error is telling you.
<asp:GridView ID="GridView1" runat="server"
DataSourceID="yourdatasource">
<Columns>
<!-- ... -->
</Columns>
</asp:GridView>
Find the DataSourceID
in your markup and remove it, as you are setting it in your code-behind cs file:
GridView1.DataSource = dt;
GridView1.DataBind();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.