none
Proper DataContext/ItemsSource for DataGrid RRS feed

  • Question

  • I'm working with the WPF DataGrid and LINQ TO SQL. I've been reading that the proper way to manage a DataContext is to create it, do what you need to do, and be done with it. With regard to populating a DataGrid, this would seem to be different.

    What I have done is made a static class that has a static DataContext:

        private static string connectionString = global::ScScaleLoad.Properties.Settings.Default.SQLScrpDbConnectionString;
        private static SQLScrpDbDataContext _db = new SQLScrpDbDataContext(connectionString);
    

    and then a static poperty to return my ItemsSource:

        public static IEnumerable<JobOrdTable> OrderDataList
        {
          get
          {
            _db.Connection.Open();
    
            string PlantId = Plant.Id;
            try {
              return from c in _db.JobOrdTables
                  where c.OrdMixID == "SCALE"
                  && c.OrdPltId == PlantId
                  && c.JobOrdStatus != (short)JOBSTATUS.Setup
                  && c.JobOrdStatus != (short)JOBSTATUS.Complete
                  orderby c.JobStartDate descending
                  select c;
            } catch (Exception ex) {
              CEAL.CEALException("Exception building order list", ex);
              return null;
            } finally {
              _db.Connection.Close();
            }
          }
        }
    
    

    and then set the DataGrid's ItemsSource:

    JobListGrid.ItemsSource = AppData.OrderDataList;

    So, this works, but obviously my DataContext is (or maybe needs to be) living for the life of the application. Am I doing this correctly in some best practice?

     

    Thanks,

     


    Bill McCormick -- MSDN Subscriber
    Monday, May 3, 2010 9:19 PM

Answers

All replies