Home > OS >  How to update DataGridView from BindingList C#
How to update DataGridView from BindingList C#

Time:03-06

I have a Windows Forms application. It has a DataGridView called dgvCalendar. The dgv pulls data from a database, and I've confirmed (as far as I know how to) that there are no issues there.

The form also has has two buttons: btnAll, which displays all of the appointments in the calendar and works as expected; btnMonth which should show only the appointments in the current month.

I've confirmed that there is at least 1 appointment in my current month, but when I click that button, the dgv just goes blank.

If I click the btnAll, it populates again as expected.

public partial class Main: Form
{
    // I know that this populates from the database correctly
    static BindingList<Appointment> allAppts = DbManager.GetAppointmentsByUserId();

//...

private void btnAll_Click(object sender, EventArgs e)
{
    // This works just fine
    dgvCalendar.DataSource = null;
    dgvCalendar.DataSource = allAppts;
}

private void btnMonth_Click(object sender, EventArgs e)
{

    // THIS IS WHERE THE TROUBLE IS...

    DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
    System.Globalization.Calendar cal = dfi.Calendar;

    // MessageBox output is "My Month: 3" which is what I expect (it's March)
    MessageBox.Show("My Month: "   DateTime.Now.Month.ToString()); 
    
    dgvCalendar.DataSource = null;
    dgvCalendar.DataSource = allAppts.Where( 
        a => DateTime.Parse(a.start).Month == DateTime.Now.Month
    ); 
}

//...

}

CodePudding user response:

I am pretty sure that the problem is when the code is filtering the BindingList. When the code applies the filter like…

dgvCalendar.DataSource = allAppts.Where(
         a => DateTime.Parse(a.start).Month == DateTime.Now.Month);

this is returning an IEnumerable<Appointment>, which the grid obviously does not handle.

Fortunately, converting the IEnumerable to a list by adding .ToList() to the end of the line of code should display the filtered data in the grid as expected. Something like…

dgvCalendar.DataSource = allAppts.Where(
         a => DateTime.Parse(a.start).Month == DateTime.Now.Month).ToList();

Also, it appears you are storing the dates as a string which is only going to create more work for you. I suggest you store the dates as DateTime objects.

  • Related