2014-02-06 82 views
1

當我嘗試加載datagridview asyncroon時,我收到一條InvalidOperationException異常消息:「由於對象的當前狀態,操作無效」。 當我添加一個項目到BindingList並且調用是重要時,會發生這種情況。沒有線程不會拋出異常。任何幫助深表感謝。Asynchoon加載datagridview綁定列表時出現異常

這些都是我用項目添加到DataGridView方法:

public static class ExtensionMethods 
{ 
    public static void LoadAsync<T>(this DataGridView gv, IEnumerable<T> enumerable) 
    { 
     gv.DataSource = new BindingList<T>(); 
     new Thread(() => gv.LoadItems(enumerable)) { IsBackground = true, Name = "AsyncLoad" }.Start(); 
    } 

    private static void LoadItems<T>(this DataGridView gv, IEnumerable<T> enumerable) 
    { 
     foreach (T item in enumerable)   
      gv.AddItemToDataSourche(item);   
    } 

    private static void AddItemToDataSourche<T>(this DataGridView gv, T item) 
    { 
     if (gv.InvokeRequired) 
      gv.Invoke(new Action(() => gv.AddItemToDataSourche(item))); 
     else 
      ((BindingList<T>)gv.DataSource).Add(item); //This is where it goes wrong. 
    } 
} 

我這是怎麼實例化的DataGridView:

public partial class Form1 : Form 
{ 
    private DataGridView _gv = new DataGridView(); 
    private readonly IEnumerable<Person> _persons = new List<Person> 
     { 
      new Person {ID = 1, FirstName = "Test 1", LastName = "Someone"}, 
      new Person {ID = 2, FirstName = "Test 2", LastName = "Someone"}, 
      new Person {ID = 3, FirstName = "Test 3", LastName = "Someone"} 
     }; 

    public Form1() 
    { 
     InitializeComponent(); 
     Controls.Add(_gv); 
     _gv.LoadAsync(_persons);    
    } 
} 

public class Person 
{ 
    public int ID { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

回答

0

我不認爲DataGridView控件處於就緒狀態,所以它不會在構造函數中工作,並且Load方法似乎爲時尚早,所以請嘗試使用OnShown替代方法:

protected override void OnShown(EventArgs e) { 
    base.OnShown(e); 
    _gv.LoadAsync(_persons); 
} 
相關問題