- VBForums
- .NET and More
- C#
- [RESOLVED] System.InvalidCastException: System.Data.SQLite.SQLiteDataReader cast to byte[]
-
Sep 5th, 2021, 08:34 AM
#1
Thread Starter
Fanatic Member
[RESOLVED] System.InvalidCastException: System.Data.SQLite.SQLiteDataReader cast to byte[]
My Sqlite DB column ImageBlob is Image type, can be NULL. When the image is NULL, I get System.InvalidCastException. How to check whether it is NULL before doing the cast?
if (reader!= DBNull.Value && reader!= null) is not enough.
Code:
public static object ExecutSqlCommand(string cmdText)
if (sqliteConn!= null)
{
using (DbCommand dbCommand = sqliteConn.CreateCommand())
{
dbCommand.CommandText = cmdText;
return dbCommand.ExecuteReader();
}
return null;
}
object reader= null;
reader= ExecutSqlCommand("SELECT ImageBlob FROM MySettings WHERE F='cmd'");
string bitmapUTF8String;
if (reader!= DBNull.Value && reader!= null)
{
byte[] blobs = (byte[])reader; //<--- error System.InvalidCastException
bitmapUTF8String = Encoding.UTF8.GetString(blobs);
}
-
Sep 5th, 2021, 08:58 AM
#2
Re: System.InvalidCastException: System.Data.SQLite.SQLiteDataReader cast to byte[]
You need to check if the column is null, not the reader itself.
-
Sep 5th, 2021, 09:11 AM
#3
Re: System.InvalidCastException: System.Data.SQLite.SQLiteDataReader cast to byte[]
vb.net Code:
if (reader.Read() && !reader.IsDBNull(reader.GetOrdinal("ColumnName")))
{
var data = (byte())reader["ColumnName"];
// Use data here.
}
-
Sep 5th, 2021, 10:42 PM
#4
Thread Starter
Fanatic Member
Re: System.InvalidCastException: System.Data.SQLite.SQLiteDataReader cast to byte[]
Originally Posted by jmcilhinney
vb.net Code:
if (reader.Read() && !reader.IsDBNull(reader.GetOrdinal("ColumnName")))
{
var data = (byte())reader["ColumnName"];
// Use data here.
}
Thank you. (byte())reader["ColumnName"] solve my problem.
-
Sep 6th, 2021, 12:44 AM
#5
Re: [RESOLVED] System.InvalidCastException: System.Data.SQLite.SQLiteDataReader cast
If you're only getting one value then you shouldn't be calling ExecuteReader in the first place. ExecuteScalar exists for that purpose. You can call ExecuteScalar and it will return the value as an Object reference or DBNull.Value if there is not data. E.g.
vb.net Code:
var data = myCommand.ExecuteScalar() as byte[];
if (data != null)
{
// Use data here.
}
as performs a conditional cast, so data will be null if ExecuteScalar returns DBNull.Value.
- VBForums
- .NET and More
- C#
- [RESOLVED] System.InvalidCastException: System.Data.SQLite.SQLiteDataReader cast to byte[]
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|