I'm using :
string date1 = reader. GetDateTime(reader. GetOrdinal("firstMove"). ToString()
But it's throwing an exception especially if the value is null....
I'm using :
string date1 = reader. GetDateTime(reader. GetOrdinal("firstMove"). ToString()
But it's throwing an exception especially if the value is null....
Try the below code.
string date1=reader["coloumn name"].tostring();
The fact you're getting an exception would be easier to solve if you told us what kind of exception you get. Possible errors are:
DateTime
, thus GetDateTime
doesn't work at allfirstMove
is not a valid column name at all, so you can not access that columnAssuming the column really exists and is of type DateTime
I tend to use the following:
DateTime? d = reader["firstMove"] as DateTime?;
This works pretty well. What you want would read
DateTime? d = reader["firstMove"] as DateTime?;
string dstring = d.HasValue ? d.Value.ToString() : "";
Or:
string date1 = !reader.IsDBNull(reader.GetOrdinal("firstMove")) ? reader.GetDateTime(reader.GetOrdinal("firstMove").ToString() : String.Empty;
It would be better for you, to use DateTime (or a nullable DateTime - DateTime?) instead of string, to handle dates.
If you want to follow this approach, you can use an Extension Method:
public static class IDataReaderExtensions
{
public static DateTime GetDateTimeOrMinValue(this IDataReader dr, int position)
{
if (dr.IsDBNull(position))
{
return DateTime.MinValue;
}
return dr.GetDateTime(position);
}
public static DateTime? GetDateTimeOrNull(this IDataReader dr, int position)
{
if (dr.IsDBNull(position))
{
return null;
}
return dr.GetDateTime(position);
}
}
Usage:
DateTime dateA = reader.GetDateTimeOrMinValue(reader.GetOrdinal("firstMove"));
DateTime? dateB = reader.GetDateTimeOrNull(reader.GetOrdinal("firstMove"));
You can even improve the extension method, so it could receive the column name and find the ordinal position internally.
Hope this helps,
Use as below, by using or function to check whether null or not null.
if(string1 || string2 ||string3)