Validation for null value of datetime - c#

I would like to make an if else statement in my view file. if the date is not null, it will show the edited date. if its null then it will show Unavailable. But the datetime value will never be null as when I try to debug, it will show the default value 1/1/0001 12:00:00
grid.Column("edited_on", "Edited On", format: (item) =>
{
if (item.edited_on.ToString() != "")
{
return Html.Raw(string.Format("{0:dd-MMM-yyyy}", item.edited_on));
}
else
{
return Html.Raw(string.Format("Unavailable"));
}
}),
I'm expecting a way to make a condition of when the date is null

if item.edited_on is a nullable field (i.e. datetime? instead of datetime) just check
if (item.edited_on != null)
{
return Html.Raw(string.Format("{0:dd-MMM-yyyy}", item.edited_on));
}
else
{
return Html.Raw(string.Format("Unavailable"));
}
if it is not nullable you can check it against default(DateTime):
if (item.edited_on != default(DateTime))
{
return Html.Raw(string.Format("{0:dd-MMM-yyyy}", item.edited_on));
}
else
{
return Html.Raw(string.Format("Unavailable"));
}

Related

Make null columns invisible in DataGridView

I have a datagridview in WinForm C# application called custFleetDataGrid
I've tried to create a method which will set each column to invisible if all the rows are null or ""
The code does not work as expected, columns with blank data remain in the grid view.
I'm calling Code like this
custFleetDataGrid.RemoveEmptyColumns();
Method I'm using to remove NullColumns
public static class ExtensionGridView
{
public static DataGridView RemoveEmptyColumns(this DataGridView grdView)
{
foreach (DataGridViewColumn clm in grdView.Columns)
{
bool notAvailable = true;
foreach (DataGridViewRow row in grdView.Rows)
{
if (row.Cells[clm.Index].Value == null || row.Cells[clm.Index].Value.ToString() != "")
{
notAvailable = false;
break;
}
}
if (notAvailable)
{
grdView.Columns[clm.Index].Visible = false;
}
}
return grdView;
}
}
could this be because the compiler is trying to convert a null value to a string?
Correct, that's the exact case. Just it's not the compiler, but the code you have written.
I would suggest you encapsulating the empty cell logic into separate extension method inside the ExtensionGridView class:
public static bool IsEmpty(this DataGridViewCell cell)
{
var value = cell.Value;
return value == null || value == DBNull.Value || (value as string) == string.Empty;
}
Then you can use simple LINQ to determine the empty columns:
public static IEnumerable<DataGridViewColumn> EmptyColumns(this DataGridView gridView)
{
return gridView.Columns.Cast<DataGridViewColumn>()
.Where(c => gridView.Rows.Cast<DataGridViewRow>().All(r => r.Cells[c.Index].IsEmpty()));
}
Then your method could be simply like this:
public static DataGridView RemoveEmptyColumns(this DataGridView gridView)
{
foreach (var column in gridView.EmptyColumns())
column.Visible = false;
return gridView;
}
If Value is null, you'll get a NullReferenceException if using ToString() on it. So you have to null-check the value before using ToString().
Go like this:
// IF (Value is empty => use "").ToString() <-- IsNullOrEmpty
if (!string.IsNullOrEmpty(row.Cells[clm.Index].Value ?? "").ToString())
{
notAvailable = false;
break;
}
Check the details about ?? here.
Its the same as:
// If not null
if(row.Cells[clm.Index].Value != null)
{
// If string of value is empty
if(row.Cells[clm.Index].Value.ToString() != "")
{
notAvailable = false;
break;
}
}
Away from your problem here's a short version of everything:
public static DataGridView RemoveEmptyColumns(this DataGridView grdView)
{
for (int i = 0; i < grdView.ColumnCount; i++)
{
// On each iteration get all values of a column
IEnumerable<string> column = grdView.Rows.Cast<DataGridViewRow>().Select(row => (string)row.Cells[i].Value);
// If there is no value with length > 0 => visible = false
if (!column.Any(x => x.Length > 0)) { grdView.Columns[i].Visible = false; }
}
return grdView;
}
Instead of iterating trough each row i'd let my select statement do it like so:
SELECT some columns FROM yourtable WHERE thecolumn IS NOT NULL
Your problem is that you are checking if row.value.toString() is null or empty. If valueis null, when it tries to get the toString() to check if its null or empty it can't.
Change your if statement to:
if (row.Cells[clm.Index].Value != null || row.Cells[clm.Index].Value.toString()!="")
{
//Code
}
Important note:
In C# (and most modern languages) you have two opetaors for OR (| and ||) and two for AND(& &&). If its just one (&/|) it will check both sides but if it have two (&&/||) if the first condetin determines eveirthing (a true for OR or a false for AND) it will not check the second one.
This gives you more rendiment but also is usefull for not having nullpointerexeptions. If it's null, it will not check the second part and it will not explote. If you just put one it will say "Yes, is null, lets check if the string is also "" and will throw a NulPointerExeption.

Check DateTime for null in linq expression

Is where a way to check if DateTime is null in linq expression? I've IEnumeable method where I'm returning data from database
return _requestRepository.ExecuteProcReader(
myRequest,
new SqlParameter("#userName", user)).Select(items => new Feed
{
Id = (int)items[0],
Title = items[1].ToString(),
Body = items[2].ToString(),
Link = items[3].ToString(),
PubDate = (DateTime) items[4]
});
And items[4] is a datetime which can be null in database. So, how can check something like
if(items[4] is DateTime)
{
PubDate = (DateTime) items[4]
}
One more option would be to declare PubDate as nullable inside class Feeddeclaration.
Like this:
class Feed {
public DateTime? PubDate {get;set;}
...
}
This will expose truth from database into data access layer and shift your null checks one level up.
See: Nullable types in c#
May be you can use ternary operator here.
return _requestRepository.ExecuteProcReader(myRequest,new SqlParameter("#userName", user)).Select(items => new Feed
{
Id = (int)items[0],
Title = items[1].ToString(),
Body = items[2].ToString(),
Link = items[3].ToString(),
PubDate = ((DateTime)items[4]).HasValue ? (DateTime) items[4] : DateTime.Now
//Or any date you want to use
});
You should also check for DBNull.Value when getting data from a database.
Here's what I'll do :
PubDate = (item[4] == null || item[4] == DBNull.Value ? DateTime.Now : (DateTime)item[4])
If you have multiple fields that can be NULL in database, you can put it in an extension method as :
public static object GetDBValue(this object value, object defaultValue)
{
return value == null || value == DBNull.Value ? defaultValue : value;
}
And call it with :
PubDate = (DateTime)date1.GetDBValue(DateTime.Now);

GetData include sometime is Null

I get data from my database with this code
var table = kantarDataSetTartimlarTableAdapter.GetData().Select(s => new
{
s.DateColumn,
s.Index
}).AsEnumerable().Select ((s, column) => new
{
s.DateColumn,
s.Index
column_no = column + 1
});
If date column is not null I haven't got any problem. But when date column have null data I have a problem:
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public System.DateTime event_start_date {
get {
try {
return ((global::System.DateTime)(this[this.tableDataTable1.event_start_dateColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'event_start_date\' in table \'DataTable1\' is DBNull.", e);
}
}
set {
this[this.tableDataTable1.event_start_dateColumn] = value;
}
}
How can I solve this error?
It appears your DB column & entity model are out of sync. If you are getting a null value back from the database then that field must be nullable. For that to map across to your model it must also support nullable dates.
You need to update event_start_date in your model to use Nullable<DateTime>/DateTime?.
You may try providing a default value when reading the value from your database to ensure you aren't storing any nulls:
DateColumn = s.DateColumn ?? DateTime.MinValue
I update event_start_date and I solve my problem
get {
try {
if (this[this.table.DateTimeColumn] is DBNull)
{
return Convert.ToDateTime(null);
}
else
{
return ((global::System.DateTime)(this[this.table.DateTimeColumn]));
}
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("Description", e);
}
}
set {
this[this.table.DateTimeColumn] = value;
}

linq check if matches null or selected item

I am checking to see if items already match whats in my MSSQL DB. I am using LINQ to update records. I would like to know how i can check if an item is equal to d_0_2 or if its equal to null/empty. How would i go about doing this?
below is my existing code, which partially works. but is failing due to the null/Empty
if (updateProduct.studioId == Convert.ToInt32(d_0_2.SelectedValue)) { }
else { updateProduct.studioId = Convert.ToInt32(d_0_2.SelectedValue);}
Thanks in advance.
I'm not sure if I understood you question correctly, but you want to check if item is null or if not is it studioId equal to d_0_2.SelectedValue
if (updateProduct == null)
{
//create new update product
}
else if (updateProduct.studioId != Convert.ToInt32(d_0_2.SelectedValue))
{
updateProduct.studioId = Convert.ToInt32(d_0_2.SelectedValue);
}
string value = d_0_2.SelectedValue.ToString();
// what if SelectedValue is empty or null?
if (!string.IsNullOrEmpty(value))
return;
// what if product is null?
if (updateProduct != null)
return;
if (updateProduct.studioId != null &&
updateProduct.studioId == Convert.ToInt32(value))
{
// you have product and its id equal to d_0_2.SelectedValue
}
else
{
// studioId not equal to to d_0_2.SelectedValue
updateProduct.studioId = Convert.ToInt32(value);
}

Set Null value in DateTimePicker in C#

I am developing a winform based Desktop application in C#. I would like the user to set the DateTimePicker to Null. I am developing a search box, and would like to ignore the date if it is set to Null
Here is what I am doing :
this.dateTimePicker2.CustomFormat = " ";
this.dateTimePicker2.Format = DateTimePickerFormat.Custom;
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
this.dateTimePicker2.CustomFormat = "dd-MM-yy";
}
So far so good. However, once the user selects the date, the dateTimePicker2 control shows some date ( the date the user has selected). There is no way to set the date to null again. I am not keen to enable the checkbox associated with the datetimepicker control.
I was wondering if it is possible to set the datetimepicker date to null.
Thanks
This is in reference from a post that is old but other users on this site have posted it here you go
// Use ValueChanged to decide if the value should be displayed:
dateTimePicker1.ValueChanged += (s, e) => { dateTimePicker1.CustomFormat = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ? "MM/dd/yyyy" : " "; };
//When getting the value back out, use something like the following:
DateTime? dt = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ? (DateTime?) dateTimePicker1.Value : null;
// or
DateTime dt2 = (dateTimePicker1.Checked && dateTimePicker1.Value != dateTimePicker1.MinDate) ? dateTimePicker1.Value : DateTime.MinValue;
or you can set the CustomFormat to " " an empty space like the following below
dateTimePicker1.CustomFormat= " ";
Add checkbox to your datetime picker property:
string datevalue = dateTimePicker2.Checked != true ? "N/A": dateTimePicker2.Text;**
I dont think its possible because DateTime is not nullable.
But you could use DateTime.MinValue this way tou can still compare easily
if (datetimepicker.DateTime == DateTime.MinValue)
{
// just as good as null, maybe
}
I was wondering if it is possible to set the datetimepicker date to null
There's no way to set DateTimePicker.Value to null, because its type isn't nullable. MSDN says, that:
If the Value property has not been changed in code or by the user, it
is set to the current date and time (DateTime.Now).
But this isn't a problem. You should set to null some bound property, not the DateTimePicker.Value:
public class MyModel : INotifyPropertyChanged
{
public DateTime? DateTimeFilter
{
get { return dateTimeFilter; }
set
{
if (dateTimeFilter != value)
{
dateTimeFilter = value;
OnPropertyChanged("DateTimeFilter");
}
}
}
private DateTime? dateTimeFilter;
// INotifyPropertyChanged implementation is omitted
}
public partial class Form1 : Form
{
private readonly MyModel model;
public Form1()
{
InitializeComponent();
model = new MyModel();
dateTimePicker1.DataBindings.Add("Value", model, "DateTimeFilter", true, DataSourceUpdateMode.OnPropertyChanged, DateTime.Now);
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(model.DateTimeFilter.HasValue ? string.Format("User has selected '{0}'.", model.DateTimeFilter) : "User hasn't selected anything.");
}
private void button2_Click(object sender, EventArgs e)
{
// here's the data binding magic: our model's property becomes null,
// and datetimepicker's value becomes DateTime.Now, as it was initially set
model.DateTimeFilter = null;
}
}
DateTime is not nullable type.
But you can do this trick:
Just add a checkbox on the date picker, you can find it on properties and set ShowCheckBox to True.
You can use this conditional:
if(datePicker.Checked){
//Do some stuff to ignore the Date Picker value
}
For additional info, I'm use Microsoft Visual Studio 2010, I'm not check the other IDE yet.
Hope this help. Cheers...
This worked for me when using a DateTimeControl on a SharePoint Application Page.
if (dtcOpenDate.SelectedDate != DateTime.Now)
{
item["Open Date"] = dtcOpenDate.SelectedDate;
}
This implementation replaces the original Value property with a nullable DateTime which handles the CheckBox state in the setter. The default date can be set flexibly, in my circumstance a start of year date is easier to work with then min value or today. Setting a custom format of " " when null i felt doesn't improve to user experience but feel free to change, I chose to keep it simple.
public class DateTimePickerAdvanced : DateTimePicker
{
public DateTime DefaultDate { get; set; }
public DateTimePickerAdvanced()
{
DefaultDate = new DateTime(2020, 01, 01);
}
public new DateTime? Value
{
get
{
return this.ShowCheckBox && !this.Checked ? null : (DateTime?)base.Value;
}
set
{
if (value == null && !this.ShowCheckBox)
{
throw new Exception("ShowCheckBox must be enabled in order to set DateTimePicker to null");
}
base.Value = value == null ? DefaultDate : (DateTime)value;
if (this.ShowCheckBox)
{
if (value == null && this.Checked)
{
this.Checked = false;
}
else if (value != null && !this.Checked)
{
this.Checked = true;
}
}
}
}
}

Categories

Resources