Hi I have to display student image on image box while selecting student ID from drop down list. The image is store in binary format in db.I want to display the image without using generic http handler. While using the given below code generation one error. The error is "Cannot convert type string to byte[]". Please help me.
Code:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet1TableAdapters.TextBoxTableTableAdapter tx;
tx = new DataSet1TableAdapters.TextBoxTableTableAdapter();
DataTable dt = new DataTable();
dt = tx.GetstudData(int.Parse(DropDownList1.SelectedValue));
foreach (DataRow row in dt.Rows)
{
TextBox1.Text = (row["FirstName"].ToString());
TextBox2.Text = (row["SecondName"].ToString());
byte[] barrImg = (byte[])(row["StudImage"].ToString());
string base64String = Convert.ToBase64String(barrImg , 0, barrImg.Length);
Image1.ImageUrl = "data:image/png;base64," + base64String;
}
}
SQL Query:
SELECT FirstName, SecondName, StudentImage FROM TextBoxTable WHERE (Id = @Id)
Aspx Source:
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Image ID="Image1" runat="server" />
</div>
Data Base:
Yes, the problem is here:
byte[] barrImg = (byte[])(row["StudImage"].ToString());
You're calling ToString()
on row["StudImage"]
. That will result in a String
. You're then casting that string to byte[]
- but that doesn't work, because there's no such conversion. (What would you expect it to do?)
It's not clear why you're calling ToString
at all - if the value is binary data, I'd expect this to work:
byte[] barrImg = (byte[]) row["StudImage"];
Note that you don't need to provide three arguments to Convert.ToBase64String
- you can just use:
string base64 = Convert.ToBase64String(barrImg);
I'd personally encourage you to use casting for your earlier statements as well - if the values aren't strings, then presumably that represents a serious issue:
TextBox1.Text = (string) row["FirstName"];
TextBox2.Text = (string) row["SecondName"];
On the other hand, your schema allows for null values - which currently you're not taking into consideration at all. All of the casts above will throw an exception if the values is actually DbNull.Value
. You should consider how you want to handle that, as a separate matter.
See more on this question at Stackoverflow