I have no values to insert into MaxPrice or MinPrice columns which can be null. The values when they don't exist are originally were seen as , , in the resulting Sql expression. I got a syntax error before and changed the code to this
(setItem.MinPrice.ToString()!="")?setItem.MinPrice.ToString() : null,
(setItem.MaxPrice.ToString() != "") ? setItem.MaxPrice.ToString() : null
But when I execute this I get an error and the sql still looks like the , , . The columns are decimal but can be NULL.
Use parameters. Always.
cmd.Parameters.AddWithValue("#minPrice",
setItem.MinPrice == null ? DBNull.Value : (object)setItem.MinPrice);
cmd.Parameters.AddWithValue("#maxPrice",
setItem.MaxPrice == null ? DBNull.Value : (object)setItem.MaxPrice);
or with a tool like Dapper:
// adds "#MinPrice" and "#MaxPrice" correctly as parameters, as long
// as the sql contains those tokens in some way
conn.Execute(sql, new { setItem.MinPrice, setItem.MaxPrice });
The bad fix - do not use - would be to supply the literal "null" in your concatenation. There are many many reasons not to do this:
// bad code; do not use
(setItem.MinPrice.ToString() != "") ? setItem.MinPrice.ToString() : "null",
(setItem.MaxPrice.ToString() != "") ? setItem.MaxPrice.ToString() : "null"
Related
I am selecting information from a database of mostly strings, however I have a datatype of number which if that value in the db is null I would like it to display as blank in my grid. I've tried reading the number in as a string but it is not working.
AccountUid = dr["ACCOUNT_UID"] == DBNull.Value ? null: Convert.ToInt32(dr["ACCOUNT_UID"])
I'm not sure what to put in where null is to get a db value of null to display as nothing. AccountUid is an int?.
Below is how I got it to work. So I was close I just needed to add (int?) to null and it works now.
AccountUid = dr["ACCOUNT_UID"] == DBNull.Value ? (int?)null : Convert.ToInt32(dr["ACCOUNT_UID"])
I am trying to make the optional parameter of a C# Method to be converted to DBNull (if it is null) to be added with Parameter.AddWithValue method.
I saw many solutions (Set a database value to null with a SqlCommand + parameters), extension methods, etc, but i wanted a single line solution.
command.Parameters.AddWithValue("#Municipio", municipio ?? DBNull.Value)don't work (Operator '??' cannot be applied to operands of type 'string' and 'System.DBNull')
The method: public static void Foo(string bar, string municipio = null)
Unfortunately i can't do string municipio = DBNull.Value because "default parameter must be a compile-time constant" (what i don't exactly understand the meaning).
I was able to make it work as such:
object obj = municipio == null ? command.Parameters.AddWithValue("#Municipio", DBNull.Value) : command.Parameters.AddWithValue("#Municipio", municipio);
I am very uncomfortable with this, seems like a JavaScript way of doing, i want something like:
if municipio == null ? command.Parameters.AddWithValue("#Municipio", DBNull.Value) : command.Parameters.AddWithValue("#Municipio", municipio);
But somehow i am not being able to make it work like this, perhaps im missing some syntax (i tried many parenthesis/etc combinations).
So my question is, is it good practice the one-line solution i reached, or should i replace it?
Updated to handle if the variable is not initialized.
Here is an example:
OracleParameter P_COUNTYCODE = new OracleParameter("P_COUNTYCODE", OracleDbType.Varchar2);
P_COUNTYCODE.Direction = ParameterDirection.Input;
P_COUNTYCODE.Value = countyCode.Length > 0 ? countyCode : (object)DBNull.Value;
try:
command.Parameters.AddWithValue("#Municipio", !string.IsNullOrEmpty(municipio) > 0 ? municipio : (object)DBNull.Value)
I've been struggling with one problem these past few hours.
I keep getting an error and it tells me that the specified cast is not valid. I'm able to change the values on the database using the stored procedure. However, when I try doing it with the executable I get that error.
This is the error
System.InvalidCastException: Specified cast is not valid.
at Administrator_Panel.DB.ReadAccountInfo(String UserID, In32& Count)
This is the code.
public static Account ReadAccountInfo(string UserID, out int Count)
if (Reader.Read())
ReturnValue = new Account((int)Reader["UserUID"],
(string)Reader["Pw"],
(bool)Reader["Admin"],
(bool)Reader["Staff"],
(short)Reader["Status"],
(int)Reader["Point"],
(int)Reader["DaemonPoints"]);
Any help would be appreciated. :) Thank you
See this answer: How to (efficiently) convert (cast?) a SqlDataReader field to its corresponding c# type?
You can't just cast SqlDataReader fields to their corresponding value types because of the possibility of nulls. You can use nullable types but it's likely your Account object isn't setup to take nullable types.
One way you can try to handle this is to add null checking:
ReturnValue = new Account(Reader["UserUID"] == DBNull.Value ? 0 : (int)Reader["UserUID"] ,
Reader["Pw"] == DBNull.Value ? "" : Reader["Pw"].ToString(),
Reader["Admin"] == DBNull.Value ? false : (bool)Reader["Admin"],
Reader["Staff"] == DBNull.Value ? false : (bool)Reader["Staff"],
Reader["Status"] == DBNull.Value ? (short) 0 : (short)Reader["Status"],
Reader["Point"] == DBNull.Value ? 0 : (int)Reader["Point"],
Reader["DaemonPoints"] == DBNull.Value ? 0 : (int)Reader["DaemonPoints"]);
How can I check if any key from json object have null value
JsonObject itemObject = itemValue.GetObject();
string id = itemObject["id"].GetString() == null ? "" : itemObject["id"].GetString();
this is my code but app crashes on it if null value for key "id"
IJsonValue idValue = itemObject.GetNamedValue("id");
if ( idValue.ValueType == JsonValueType.Null)
{
// is Null
}
else if (idValue.ValueType == JsonValueType.String)
{
string id = idValue.GetString();
}
If you do this too much, consider adding extension methods.
To do the opposite use:
IJsonValue value = JsonValue.CreateNullValue();
Read here more about null values.
http://msdn.microsoft.com/en-us/library/ms173224.aspx
The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.
if itemObject["id"] is null then the method null.GetString() doesn't exist and you'll get the error specified (null object never has any methods/fields/properties).
string id = itemObject["id"] == null ? (string)null : itemObject["id"].GetString(); // (string)null is an alternative to "", both are valid null representations for a string, but you should use whichever is your preference consistently to avoid errors further down the line
the above avoids calling .GetString() until you've asserted that the ID isn't null (check here for more in-depth), if you're using C#6 you should be able to use the new shorthand:
string id = itemObject["id"]?.GetString();
Here is solution for the issue
string id = itemObject["id"].ValueType == JsonValueType.Null ? "" : itemObject["id"].GetString();
I am trying to populate a combobox with a list my query returns. When I execute my program it gives me a specified cast is not valid error ( I have it execute on page load event). Every field in the database I have to work with can be null except the primary key. So I tried using DBNull.Value but it can't get my (int)reader fields to work. I have supplied my code below for a better understanding. How can I get my (int)reader's to work with my statements, so they can read when there is a null value?
CustData cd = new CustData();
cd.CustomerID = (int)reader["CustomerID"];
cd.Name = reader["Name"] != DBNull.Value ? reader["Name"].ToString() : string.Empty;
cd.ShippingAddress = reader["ShippingAddress"] != DBNull.Value ? reader["ShippingAddress"].ToString() : string.Empty;
cd.ShippingCity = reader["ShippingCity"] != DBNull.Value ? reader["ShippingCity"].ToString() : string.Empty;
cd.ShippingState = reader["ShippingState"] != DBNull.Value ? reader["ShippingState"].ToString() : string.Empty;
cd.ShippingZip = (int)reader["ShippingZip"];
cd.BillingAddress = reader["BillingAddress"] != DBNull.Value ? reader["BillingAddress"].ToString() : string.Empty;
cd.BillingCity = reader["BillingCity"] != DBNull.Value ? reader["BillingCity"].ToString() : string.Empty;
cd.BillingState = reader["BillingState"] != DBNull.Value ? reader["BillingState"].ToString() : string.Empty;
cd.BillingZip = (int)reader["BillingZip"];
cd.Territory = reader["Territory"] != DBNull.Value ? reader["Territory"].ToString() : string.Empty;
cd.Category = reader["Category"] != DBNull.Value ? reader["Category"].ToString() : string.Emptyy
That is because int is not nullable. You need to use int? or nullable<int> (long hand) to allow it to be an int OR a null value.
You can then use the usual .HasValue and .Value etc to get the value from the item.
EDIT: To enhance the visibility of my comment to this answer. I would advise against checking for NULL and storing Zero into your property because then when you save back you are changing a Null to a Zero even though nothing has been changed by the system. Now, reports etc may distinguish between NULL and Zero (very often) and could start doing strange things!
Null does NOT equal zero!! If you assume it does as a work around... What happens if I truly do want to record zero? How do you differentiate between a real zero and a "was null now zero" trick? Do it right, save yourself the pain!
Use nullable int, or just make your control for your int's too
reader["ShippingZip"] != DBNull.Value ? (int)reader["ShippingZip"] : default(int);
You should use a nullable int for your variable and cast it, like (int?). Int can only have a value; nullable types can also be null. When you use a nullable type, you can look at the property .HasValue. Here is the MSDN page: http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx