-1
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
}

private void btnAddGroup_Click(object sender, RoutedEventArgs e)
{  
    if (bw.IsBusy != true)
    {
        bw.RunWorkerAsync();
    }   
}

System.Timers.Timer timer = null;

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    timer = new System.Timers.Timer();
    timer.Interval = 1000;
    timer.Enabled = true;
    timer.Elapsed += new ElapsedEventHandler(UpdateChatContent);
}

public void UpdateChatContent()
{
    var myVar=(from a in db  select a).tolist();
    datagrid1.itemsSource=myVar;//here is the exception occurs
}
Samuel Slade
  • 8,405
  • 6
  • 33
  • 55
Sibasis jena
  • 32
  • 1
  • 7
  • 3
    Seems pretty self explanatory? You can't access the data grid, as it was created on another thread. – Adam Wright Jan 20 '12 at 11:41
  • 1
    [Possible duplicate](http://stackoverflow.com/q/2728896/308012). Also, for future reference when posting questions, it is helpful to give an introduction and description of your problem, rather than just posting your code. If a problem is obvious enough that you can understand the problem just from a code post, then chances are if you search for your issue (e.g. via [Google](http://goo.gl/GC3Om) or [StackOverflow](http://goo.gl/M8E1X)) then you will likely find the solution. – Samuel Slade Jan 20 '12 at 11:48
  • instead of using timer and calling UpdateChatContent on elapsed, you can use the ProgressChanged event of the background worker component and that event also permits updating the UI controls.. – S2S2 Jan 20 '12 at 11:48
  • Then how can i assign myvar to datagrid1'itemsSource Can You explain how it is done – Sibasis jena Jan 20 '12 at 11:51

1 Answers1

3

For accessing UI elements in WPF you have to do the accessing on the UI Thread. It should work if you change the code like this:

public void UpdateChatContent()
{
    var myVar=(from a in db select a).Tolist();
    OnUIThread(() => datagrid1.ItemsSource=myVar);
}

private void OnUIThread(Action action)
{
    if(Dispatcher.CheckAccess())
    {
        action();
    }
    else
    {
        // if you don't want to block the current thread while action is
        // executed, you can also call Dispatcher.BeginInvoke(action);
        Dispatcher.Invoke(action);
    }
}
Nuffin
  • 3,882
  • 18
  • 34