none
LINQ query syntax needed to populate a form filter RRS feed

  • Question

  • I want to set up a form filter using a LINQ query that will pull unique year values from the database....so if records exist for the past few years, the combobox will contain the values 2009, 2010 and 2011 as filter values that can be selected.  I can populate the filter combobox with full date values, but have been unable to figure out how to just capture the unique year values.

    Here's what I have so far but it throws an error (The argument 'value' was the wrong type. Expected 'System.DateTime'. Actual 'System.Nullable`1[System.DateTime]'.)

                using (DBContext dbc = new DBContext(connectionString))
                {                
                    cbxYear.Items.Clear();
    
                    var records = (from c in dbc.Collision
                                      orderby c.Collision_date
                                      select ((DateTime)c.Collision_date).Year.ToString()).Distinct();
    
                    cbxYear.Items.AddRange(records.ToArray());                
                }
    

     


     

    Monday, October 31, 2011 8:00 PM

Answers

  • I jabberpunch,

    You should be able to just do this and it should work:

       using (DBContext dbc = new DBContext(connectionString))
                {                
                    cbxYear.Items.Clear();
    
                    var records = (from c in dbc.Collision
                                      orderby c.Collision_date
                                      select c.Collision_date.Value.Year).Distinct();
    
                    cbxYear.DataSource = records;
                }
     
    
    
    

     


    Tom Overton
    • Marked as answer by jabberpunch Monday, October 31, 2011 10:20 PM
    Monday, October 31, 2011 8:56 PM

All replies

  • I jabberpunch,

    You should be able to just do this and it should work:

       using (DBContext dbc = new DBContext(connectionString))
                {                
                    cbxYear.Items.Clear();
    
                    var records = (from c in dbc.Collision
                                      orderby c.Collision_date
                                      select c.Collision_date.Value.Year).Distinct();
    
                    cbxYear.DataSource = records;
                }
     
    
    
    

     


    Tom Overton
    • Marked as answer by jabberpunch Monday, October 31, 2011 10:20 PM
    Monday, October 31, 2011 8:56 PM
  • Yes it does work 100% exactly perfect...thank you!
    Monday, October 31, 2011 10:20 PM