Click here to Skip to main content
15,905,233 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.


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()); // error shown here
            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:

    <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" />

Try this:

byte[] toBytes = Encoding.ASCII.GetBytes(somestring);
Share this answer
You can't convert a string to a byte array directly, because a string is (normally) made of unicode characters, which don't "map" directly to single bytes - they are variable length values.

You can do it, but you have to tell it explicitly what type of data the string contains:
string s = ...
byte[] bytes = System.Text.Encoding.Unicode.GetBytes(s);

But...unless you have been a bit silly, your image should not be in a string based column in your database at all: it should be in a byte based datatype instead.
See here: Why do I get a "Parameter is not valid." exception when I read an image from my database?[^] - it talks about how to insert and extract images from your database correctly.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900