How can I put a null value on datetime variable type?
I tried to make it nullable value, but I need to use it in ReportParameter() method to send it to my report but ReportParameter() constructor cannot take a nullable value and the ReportParameter() take just a string values!
The various constructor overloads for ReportParameter only take in a string or string array as acceptable input.
And the ReportParameter.Values property itself is actually a StringCollection in order to force the serialization to happen at compile time.
But you can pass a null value with string typing per this thread on Passing NULL parameter from aspx page to Report Server like this:
var rp = new ReportParameter("ServiceType_cd", new string[] { null });
Or per this question Report Viewer: Set null value to Report Parameters having allow null true, you can pass in a value like this:
string str = null;
var rp = new ReportParameter("ServiceType_cd", str));
you can create FailIfNull() extension method for this purpose. Please look here for more information about extension methods.
Related
When should we pass a Value and when should we pass a Type to the constructor of ObjectParameter and why?
When attempting to get a SQL OUTPUT value out of a stored procedure, it does not appear to make a difference passing a value of 0,1,2 etc or typeof(long) for example.
var ob = new ObjectParameter("CustomerID", typeof(long));
// or new ObjectParameter("CustomerID", 0)
// both work
db.InsertCustomer(ob, "CustomerName");
var CustomerID = ob.Value;
It depends on the information you have available when you are calling the constructor. All 3, name, value and type, are available as properties of the object and can be set later in the code.
It is possible that you need to create the parameter object, you know the name, and type, but you may have the value at a later time. In that case you can call the ObjectParameter(String, Type) constructor.
If you have the name and value when creating the object, then ObjectParameter(String, Object) could be more useful.
var ob = new ObjectParameter("CustomerID", typeof(long));
var ob2 = new ObjectParameter("CustomerID", 0);
Shouldn't be the same as one is an int and one is a long.
In your case, where you are getting data out, it won't matter if you use a type of a value. However using a type makes it more verbose, easier to read, and easier to understand in my opinion. It can prevent any mistakes such as int vs long.
I have an initial snippet which deserealized parameters, checks for value and handles the error:
var param = js.Deserialize<int?>(jqData.Params);
if (param.HasValue)
{
resp.ReturnValue = param.Value;
}
else
{
//handle error code
}
Now, during my modification, I have changed the method to accept a list of class parameters instead of nullable integers
var param = js.Deserialize<ClassName>(jqData.Params);
Now it invalidates .HasValue and .Value methods.
My question is: How do I properly modify these two lines so it would hold the same meaning as initial if statement?
Thus far I only thought about switching to if (param != null), but I cannot think of proper equivalent to .Value.
As soon as ClassName is a class (see - a reference type) you just need to check if it is not null.
If it is not - then the variable holds a reference to an object that you use as-is.
I am trying to retrieve a value from a List. The list is already filled but I keep getting an error saying Object reference not set to an instance of an object when I try to execute this code:
I created a global variable
private static readonly string _isDevItemParamName = "#DevItem";
In my method I call:
var devItem = sqlParams.Where(p => p.ParameterName == _isDevItemParamName).First();
This is where the error seems to occur when I do breakpoints.
Check sqlParams is null or contains any parameters and also use firstordefault instead of first because if the parameter is not available it should not through any exception.
I've got a C# method that takes a bunch of parameters, all of which have default values. One of the parameters is a List. I can't figure out how to specify that the List should default to empty. Here's what it looks like:
public static void execute(
String condition = "Unnamed condition",
List<String> messages,
Object actual = null,
Object expected = null)
I can't quite figure out how to specify that messages should be empty by default. When I enter:
...
List<String> messages = new List<String> ()
...
it complains that "default parameter value for 'messages' must be a compile-time constant".
Any ideas?
Because default parameter values must be compile-time expressions, the only acceptable default parameter value for reference types is null.
You can get around this with an overload, though:
public static void execute(String condition = "Unnamed condition")
{
execute(condition, new List<String>(), null, null);
}
Or constructing a list if the argument is null. If you must need a list and want to treat all null as an empty list, this would also handle if they called with null explicitly.
public static void execute(String condition = "Unnamed condition",
List<String> messages = null, Object actual = null,
Object expected = null)
{
// if you really want this to be empty if null, can check and assign.
if (messages == null)
{
messages = new List<String>();
}
// your other logic
}
Or, if messages is only used in one place, you can use the null-coallescing operator to substitute an empty enumeration:
public static void execute(String condition = "Unnamed condition",
List<String> messages = null, Object actual = null,
Object expected = null)
{
// assuming you are using messages once for iteration or something...
foreach(var msg in messages ?? Enumerable.Empty<String>())
...
}
Though obviously a simple if-guard can be more efficient. Really depends if you want to treat it as an empty enumerable or as an empty list or just bypass logic...
As the error message clearly states, you can't arbitrary instances of reference types as default values.
All you can use are literals, consts, or null.
Instead, you can set the default to null, then write
messages = messages ?? new List<string>();
Make messages default to null as well, and within the function body check whether its null and handle it appropiately (or replace it with a new List()).
The only thing the compiler will accept here is null. If it is convenient for you, your method will need to test for this case and substitute an empty list:
if(messages==null) {
messages=new List<String>();
}
The compiler is telling you why: default arguments must be compile-time constants. Obviously a dynamically allocated and constructed list doesn't fit that description. The simplest work-around is to make the default value null, and then in your method, if the argument is null, create the actual default list.
I have asp.net form with C#, where is I am taking user information to insert in the database as usual by using Linq. well. Where as I am taking Date of birth also from the user, but if user skip to fill date text box from ui, then I am getting date like '01/01/0001' something like this, which certainly database security would not allow to store it.
So I need to check somewhere in my code that it is null or in this (above given) format. If it is null or in format '01/01/0001' then what exactly I have to do? I don't have any default
value for dates.
So what is the standard way to handle if date is null (but not mandatory).Please guide me. So many times I found myself in trap while handling null for various types.
Edited
see what i did seems it working here. but i don't think so this is standard way:
DateTime? otxtDOB = new DateTime();
if (!string.IsNullOrEmpty(DOB))
{
if (Convert.ToDateTime(DOB) != DateTime.MinValue)
{
otxtDateOfPurchese = Convert.ToDateTime(Convert.ToDateTime(DOB).ToString("dd-MMM-yyyy"));
}
else
{
otxtDOB = null;
}
}
Please confirm me is this right way ?
Making the date property Nullable (i.e. a "DateTime?") should allow it to actually be null if the user hasn't set it. (And provided your database column will allow nulls, it can be stored as null in the database)
Otherwise it's going to default to DateTime.MinValue which is what you're seeing here. And you'll have to explicity test for DateTime.MinValue when adding to the database.
DateTime is a value type (like a number), so you can't assing a null value to it. Mane people use DateTime.MinValue or DateTime.MaxValue instead, but I prefer to use nullable types:
DateTime? nullableDate;
dateSample.Value = null;
you can do some thing like this C# have some features like nullable type you can make use of
this it will save you some piece of code it will be more robust too.
Public int InsertData(int? ouId)
{
chkValue = ouId.HasValue ? ouId.Value : 0;
}
You have the option of using Nullable<DateTime> (alias DateTime?). This makes you able to handle the date as null throughout your application.
However, personally I am not to found of nullables and would prefer this second path: You can use DateTime.MinValue (which is 01/01/0001) as a meaningful constant in your application and the check for DateTime.MinValue in your data access layer.
The database, if it is an SQL Server and the field is of type smalldatetime, would overflow and throw an exception if you tried to save DateTime.MinValue. Null however, may well be stored in the database for any type.
This is how you can parse your strings into nullable types:
private delegate bool TryParseDelegate<T>(string s, out T t);
private static T? TryParseNullable<T>(string s, TryParseDelegate<T> tryParse) where T : struct
{
if (string.IsNullOrEmpty(s))
return null;
T t;
if(tryParse(s, out t))
return t;
return null;
}
with usage:
var nullableDateTime = TryParseNullable<DateTime>("01/01/0001", DateTime.TryParse);
use
DateTime dt;
if(DateTime.TryParse(DatetImeValue.Tostring(),dt)) // datetimevalue is your db value
{
datetimeproperty = dt; // in your class declare it as DateTime? datetimeproperty
}
else
{
datetimeproperty = null;
}
While displaying check for null, if its null set it empty.
[Update]
Do one thing, Keep the property nullable. In your database. Set field to allow null and in the parameter user #DateTimeParam = null.
OR A QUICK WORKAROUND MAKE THE DATABASE FIELD AND PARAMETER VARCHAR INSTEAD OF DATETIME, IN PARAMETER PASS DATETIMEVALUE.TOSHORTDATESTRING() AND ALSO CHECK IF USER SKIPS
PUT STRING.EMPTY IN PARAMETER. IN THIS MANNER IT WILL BE EASY TO YOU TO DISPLAY DATE AND TIME. YOU NEED NOT CAST OR WIPE OFF THE TIME PART IF YOU DO NOT NEED IT
obj.BirthDate = Convert.ToDateTime(string.IsNullOrEmpty(txtBirthDate.Text.ToString()) ? System.Data.SqlTypes.SqlDateTime.MinValue.Value : Convert.ToDateTime(txtBirthDate.Text.ToString()));
You can use this while passing to database.
object datetimeObj = null;
if (datetimefromUI == DateTime.MinValue) // This is put in the DateTime object by default
datetimeObj = DBNull.Value;
else
datetimeObj = datetimefromUI;
// Post datetimeObj to parameter in database...