iCosmin iCosmin - 1 year ago 92
C# Question

Get the total number of rows for the selected month WPF MVVM

I am looking for a way to count the number of days based on the selected month from a datepicker.

The date and the id field in my model are defined as:

public Nullable<System.DateTime> Date { get; set; }

public int ID { get; set; }


private DateTime _mDate = DateTime.Now;

public DateTime MDate
{

get { return _mDate; }
set
{
if (value == _mDate)
{
return;
}
else if (_selectedTabIndex == 0)
{
_mDate = value;
}

else
{
_mDate = value;
OnPropertyChanged("MDate");
SetDaysCompleted();
}

}

}


private void SetDaysCompleted()
{
int.TryParse(MDate.ToString("MM"), out int month);
DaysCompleted = Convert.ToDecimal(db.MyTable
.Where(a => (a.Date < MDate) && (int.TryParse(a.Date.ToString("MM"), out int smonth) == month))
.Select(a => a.ID).Count());
}


I hoped something like this would work but I get a "No overload for method 'ToString' takes 1 arguments" error. Can someone please suggest how should I rewrite the query or if there's a better way to get the row count from the beginning of the selected month? Thank you.

Answer Source

I may be mistaken, but I think the issue lies here:

public Nullable<System.DateTime> Date { get; set; }  
public int ID { get; set; }

Try converting the Nullable<System.DateTime> Date to System.DateTime Date first in order to be able to use .ToString("MM") on it.

Another potential issue in your code could be : Where(a=>(a.Date < MDate). Again, if I'm understanding correctly a.Date is of type DateTime? and cannot be compared to DateTime MDate

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download