wpf 如何处理字节[]中的空值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17502802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle null value in byte[]
提问by user1358072
I have binary images in the Imagecolumn of my database table, but there are some nullvalues in the Imagecolumn. So an exception is thrown at,
我的Image数据库表的列中有二进制图像,但列中有一些null值Image。所以抛出异常,
byte[] data = (byte[])ds.Tables[0].Rows[0][0]` because of null.
byte[] data = (byte[])ds.Tables[0].Rows[0][0]` 因为为空。
How to handle this?
如何处理?
Exception message,
异常消息,
Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.
无法将“System.DBNull”类型的对象转换为“System.Byte[]”类型。
My code,
我的代码,
using (var sqlConn = new SqlConnection(connstr))
{
sqlConn.Open();
ds = new DataSet();
SqlDataAdapter sqa = new SqlDataAdapter("Select Image from Templates where Shoe='" + selectedShoe + "'", sqlConn);
sqa.Fill(ds);
//i got error here
byte[] data = (byte[])ds.Tables[0].Rows[0][0];
.....
回答by Lasse V. Karlsen
You need to specifically check for DBNullin that column before attempting the cast:
DBNull在尝试强制转换之前,您需要专门检查该列:
byte[] data = null;
if (!ds.Tables[0].Rows[0].IsNull(0))
data = (byte[])ds.Tables[0].Rows[0][0];
Note that this will fail with the same type of exception if the column in question does in fact notcontain a byte array.
请注意,如果所讨论的列实际上不包含字节数组,这将因相同类型的异常而失败。
回答by Chad Stellrecht
Handling nulls at the SQL query worked for me. If your Image column is null, the ISNULL() function will return your next value (0 in this example).
在 SQL 查询中处理空值对我有用。如果您的 Image 列为空,则 ISNULL() 函数将返回您的下一个值(在此示例中为 0)。
SqlDataAdapter sqa = new SqlDataAdapter("SELECT ISNULL([Image],0) AS Image FROM Templates where Shoe='" + selectedShoe + "'", sqlConn);

