I am converting image from bytes by FromBase64String method in asp.net C# and placed in gridview field, but in gridview it showing [object object] data in the place of image.
For more clear lets see the image,
Here is CustomerMortgageModel Model,
public class CustomerMortgageModel
{
public Image DesignImage;
}
Here is FrontEnd code,
[WebMethod]
public static List<CustomerMortgageModel> GetProductList()
{
string constr = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
List<CustomerMortgageModel> customers = new List<CustomerMortgageModel>();
Service service = new Service();
using (SqlConnection con = new SqlConnection(constr))
{
string qrySelProductDetail = "select * from tbl_MortageDetail " + System.Environment.NewLine;
using (SqlCommand cmd = new SqlCommand(qrySelProductDetail, con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
// Setup image and get data stream together
System.Drawing.Image img;
System.IO.MemoryStream MS = new System.IO.MemoryStream();
if (sdr["DesignImage"].ToString() != "")
{
string k = "i" + sdr["DesignImage"].ToString();
string b64 = k.Replace(" ", "+");
byte[] b;
// Converts the base64 encoded msg to image data
b = Convert.FromBase64String(b64);
MS = new System.IO.MemoryStream(b);
//creates image
img = System.Drawing.Image.FromStream(MS);
}
else
{
img = null;
}
customers.Add(new CustomerMortgageModel
{
DesignImage = img
});
}
}
con.Close();
}
}
return customers;
}
BACKEND Code,
<asp:GridView ID="gv_productdetail" runat="server" CssClass="display compact" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<img src="data:image/jpeg;base64,<%# Eval("DesignImage") %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Well, you not noted the format of the database column, but assuming we have this markup:
Note how I put the expression right in the markup. So, now the code to load the grid will look like this:
Output:
So, there is really no need to use a stream reader here. I assume your sample markup was for this posting - and is missing some of the databound fields.
but, you can shove/toss/use the data reader object of the sql command object. No need to loop here.
It really depends on what your addtional code behind looks like. If you are using addtional rows of data, then I do recommend you consider using a datatable, since the on row data bound event, you have full use of that data row.
So, you could consider this:
But, I would only suggest above if you need the full data row during the row data bound event (which I don't know if you are using).
but, you certainly don't need near as much code as you are posting to do this. I assumed in above the sql data column type is "image", and above should also work if it was/is a binary type also.