Unable to cast object of type 'System.DBNull' to type 'System.String`
A shorter form can be used:
return (accountNumber == DBNull.Value) ? string.Empty : accountNumber.ToString()
EDIT: Haven't paid attention to ExecuteScalar. It does really return null if the field is absent in the return result. So use instead:
return (accountNumber == null) ? string.Empty : accountNumber.ToString()
How can i fix Unable to cast object of type 'System.DBNull' to type 'System.String`
try
string value = row["BOM - RIM PN"].ToString();
In case you need some extra work for null values(maybe skip them) you need additional type check.
Unable to cast object of type 'System.DBNull' to type 'System.String' in C#
You can simply change the below line. You can return the default values like empty string or zero from your query in the select statement so the below line will not give the error.
SELECT MAX(IsNull(Transaction_ID, 0)) FROM tbl_Transactions
You need to check why the value of max(Transaction_ID)
is not returning a value. It may be due the table has not any record.
string max_ID = (string)cmd.ExecuteScalar();
You can also use Convert.ToString(cmd.ExecuteScalar())
which will handle the null value exception.
if (max_ID == null || Convert.IsDBNull(max_ID.ToString()))
To
if (String.IsNullOrEmpty(max_ID))
{
//Your if block statement.
}
else
{
//Your else block statement.
}
It is because if max_ID
will be null
in that case max_ID.ToString()
will give error.
How to fix exception:Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'
That exception of "Unable to cast object of type 'System.DBNull' to type xxx" is correct and it's also quite straightforward, because the column value you are trying to convert from DataRow is DbNull.
If you are reading rows from DataTable, you should always check for DbNull if the column is typed as nullable column.
For example, the code should be like this:
var img = (byte[])(ds.Tables[0].Rows[0][0] == DbNull.Value ? null : ds.Tables[0].Rows[0][0]);
InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.Nullable`1[System.Int32]'
From DBNull Documentation:
DBNull
represents a nonexistent value, wherenull
denotes absence of
reference to the object.
To fix your issue,
Null check before changing value's type and then assign it to the variable
result.Add (
new GetActiveUserPackagesForOpenBillingPeriodResult {
Amount = (decimal) reader["Amount"],
AcceptanceActID = Convert.IsDBNull(reader["AcceptanceActID"]) ? null : (int?) reader["AcceptanceActID"],
PackageID = (int) reader["PackageID"],
UserID = (int) reader["UserID"],
AccountID = (int) reader["AccountID"],
HasChangedPackage = (bool) reader["HasChangedPackage"],
});
Unable to cast object of type 'System.DBNull' to type 'System.String'. Error
for this particular line try this:
aPartOrder.VendorId = dbReader.GetValue(5)==DBNull?"":dbReader.GetValue(5).value;
better would be to write a helper function:
private static string MyToString(object o)
{
if(o == DBNull.Value || o == null)
return "";
return o.ToString();
}
and use it:
aPartOrder.VendorId = MyToString(dbReader.GetValue(5));
Unable to cast object of type System.DBNull to type System.String
Try this
lblSNO.Text = (erow.SNO == null) ? string.Empty : erow.SNO.ToString()
or
lblSNO.Text = (erow.SNO == DBNull.Value) ? string.Empty : erow.SNO.ToString()
Unable to cast object of type 'System.DBNull' to type 'System.DateTime'
Edit suggested by mjwills
DateTime don't accept null value. Check if the value is null and assigne a default value
while (dr.Read())
{
not.Add(new NotificationModel { Datenow = ((DateTime) dr["datumnu"]).ToString("yyyy/MM/dd"), Bericht = dr["bericht"].ToString() });
}
Become
while (dr.Read())
{
DateTime defaultDateTime = DateTime.Now;
if(dr.IsNull("datumnu")){
defaultDateTime = (DateTime)dr["datumnu"];
}
not.Add(new NotificationModel { Datenow = defaultDateTime, Bericht = dr["bericht"].ToString() });
}
in single line
while (dr.Read())
{
not.Add(new NotificationModel { Datenow = (dr.IsNull("datumnu") ? DateTime.Now : (DateTime)dr["datumnu"]), Bericht = dr["bericht"].ToString() });
}
Related Topics
Selenium C# Webdriver: Wait Until Element Is Present
C# Catch a Stack Overflow Exception
Entity Framework - Include Multiple Levels of Properties
How to Get the Datetime For the Start of the Week
How to Do Joins in Linq on Multiple Fields in Single Join
How to Do Constructor Chaining in C#
Execute a Large SQL Script (With Go Commands)
Use Linq to Get Items in One List≪≫, That Are Not in Another List≪≫
Best Way to Compare Two Complex Objects
Data Binding to Selecteditem in a Wpf Treeview
Random.Next Returns Always the Same Values
Split a String by Another String in C#
Insert 2 Million Rows into SQL Server Quickly
How to Prevent And/Or Handle a Stackoverflowexception