0

I am trying to insert data from ASP.NET into SQL Server and retrieve it from SQL Server back to ASP.NET.

The insert part is done, but I am having problems to retrieve data. I am using this code, but is throwing an error:

SqlConnection con = new SqlConnection(myconnstrng);
con.Open();

SqlCommand cmd = new SqlCommand("selection", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", parameter);

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet dsa = new DataSet();
da.Fill(dsa);

if (dsa.Tables[0].Rows.Count > 0)
{
    MemoryStream ms = new MemoryStream((byte[])dsa.Tables[0].Rows[0]["Data"]);
    string strBase64 = Convert.ToBase64String(ms);
    ImageButton2.ImageUrl = "data:Image/png;base64," + strBase64;
}

and the error I got is :

Cannot convert from 'System.IO.MemoryStream' to 'byte[]'

I am new to programming, and if someone could help me about this problem.

Thanks to everyone !

0

1 Answer 1

0

The particular line you are stuck on, you don't need a MemoryStream at all. You can pass the value from the DataTable straight to ToBase64String.

But you can save yourself some bother with these tips:

  1. ALWAYS dispose the connection, command and adapter/reader correctly, by putting them in using blocks`

  2. For a single result, you can skip the table and adapter, and just use (byte[]) cmd.ExecuteScalar().

  3. If you have more than one row which you need to process (as opposed to just displaying in a grid view), you may find it again easier to skip the DataTable and grab data out via this:

using(var reader = cmd.ExecuteReader())
{
    while(reader.Read())
        DoSomethingWithResult(reader.IsDBNull(0) ? null : reader.GetBytes(0));
}

Generally, DoSomethingWithResult should not be very heavy processing, or you will block the SQL server. If so, store in memory and process it afterwards.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.