Search code examples
entity-frameworklinqdatagridviewlinq-to-entities

Clear DataGridView datasource linked to Entity Framework


I'm new to Entity Framework, I have a DataGridView connected to Entity Framework as it shown below

dgvDebit.DataSource = (from daily in accountingEntities.DailyAccounts
                       join voucherdetails in accountingEntities.VoucherDetails on daily.DailyId equals voucherdetails.DailyId
                       where voucherdetails.VoucherId == keyvalue
                       group voucherdetails by daily.DailyName into dgroup
                       select new
                              {
                                  DailyName = dgroup.Key,
                                  SumOfDebit = dgroup.Sum(s => s.Debit)
                              }).ToList();

My question is: I want to clear DataGridView datasource but every thing I did has failed - please any help here?


Solution

  • OK, so you want to bind to an empty list of the type that you have.

    Step 1: define a .NET type for your query result return type:

    public class ResultDTO
    {
        public string DailyName { get; set; }
        public decimal SumOfDebit { get; set; }
    }
    

    Step 2: change your "normal" query to:

    dgvDebit.DataSource = (from daily in accountingEntities.DailyAccounts
                           join voucherdetails in accountingEntities.VoucherDetails on daily.DailyId equals voucherdetails.DailyId
                           where voucherdetails.VoucherId == keyvalue
                           group voucherdetails by daily.DailyName into dgroup
                           select new ResultDTO
                                  {
                                      DailyName = dgroup.Key,
                                      SumOfDebit = dgroup.Sum(s => s.Debit)
                                  }).ToList();
    

    Step 3: if you want to "clear" the DataGridView, but retain the columns, you can now use:

    dgvDebit.DataSource = new List<ResultDTO>();