Is There a Way to Convert System.Data.SqlTypes.SqlBinary of Datatable To Type System.Byte[]?

427 Views Asked by At

I have a dynamic picturebox in C# and it get the picture from a column of datatable the datatable structure is:

public DataTable Pictures = new DataTable();
Pictures.Columns.Add("id", typeof(bool));
Pictures.Columns.Add("filebytes", typeof(SqlBinary));

and i have a array of byte to show pictures in picturebox:

byte[] ImageBinary;

and the following code is for showing image:

                        PictureBox a = new PictureBox();      
                        a.Location = new Point(100, 90);
                        a.Size = new Size(25, 25);
                        a.SizeMode = PictureBoxSizeMode.StretchImage;
                        groupBox3.Controls.Add(a);
                        MemoryStream ms = null;
                        Image img = null;
                        Tools b = new Tools();
                        ImageBinary = b.CreateImageBinary(openFileDialog1.FileName);
                        ms = new MemoryStream(ImageBinary);
                        Pictures.Rows.Add(new object[] { i, ImageBinary });
                        img = Image.FromStream(ms);
                        a.Image = img;
                        ms.Close();

it get image from a Openfiledialog

i want to assign a value to picturebox from datatable my problem is when i change the code like this:

 ImageBinary = (byte[])Pictures.Rows[sm][1]; //sm is a variable to specific a row of datatable

it get me error like:

Unable to cast object of type 'system.data.sqltypes.sqlbinary' to type 'system.byte[]'

i am confused help me please

1

There are 1 best solutions below

3
Athanasios Kataras On

You can use the DqlBinary.Explicit operator

public static explicit operator byte[] (System.Data.SqlTypes.SqlBinary x);

My suggestion would be to add the using System.Data.SqlTypes; import in the beginning of your .cs file where the explicit operator is declared.

Check the documentation for the dlls that include it in case the compiler can't find the namespace.