简体   繁体   English

有没有办法将 Datatable 的 System.Data.SqlTypes.SqlBinary 转换为 System.Byte[] 类型?

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

I have a dynamic picturebox in C# and it get the picture from a column of datatable the datatable structure is:我在 C# 中有一个动态图片框,它从一列数据表中获取图片,数据表结构是:

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它从 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[]'无法将“system.data.sqltypes.sqlbinary”类型的对象转换为“system.byte[]”类型

i am confused help me please我很困惑请帮帮我

You can use the DqlBinary.Explicit operator您可以使用DqlBinary.Explicit 运算符

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

My suggestion would be to add the using System.Data.SqlTypes;我的建议是添加using System.Data.SqlTypes; import in the beginning of your .cs file where the explicit operator is declared.在声明显式运算符的.cs文件的开头导入。

Check the documentation for the dlls that include it in case the compiler can't find the namespace.检查包含它的 dll 的文档,以防编译器找不到命名空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM