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 !
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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:
-
ALWAYS dispose the connection, command and adapter/reader correctly, by putting them in
using
blocks` -
For a single result, you can skip the table and adapter, and just use
(byte[]) cmd.ExecuteScalar()
. -
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0