2011-12-01 64 views
1

我有一個從DataGridView繼承的自定義控件。它通過一些附加功能(其導出每個單元的內容)來增強控制。我想使用此功能,但不需要網格本身的用戶界面。數據綁定不在Form.Controls集合中的DataGridView控件?

因此,我創建了自定義控件的實例,將DataSource屬性設置爲DataTable的實例,並且在網格中沒有列。我的數據表具有列(和行),AutoGenerateColumns爲true,但沒有列出現在網格「Columns」集合中。自定義控件在此處變得無關緊要,因爲DataGridView控件的功能相同。

如果我將網格添加到窗體的「控件」集合,數據綁定工作,網格有我的列。

這是爲什麼?

public Form1() 
    { 
    InitializeComponent(); 

    DataTable dataTable = new DataTable() { TableName = "Bob" }; 
    dataTable.Columns.Add("One",typeof(String)); 
    dataTable.Columns.Add("Two", typeof(String)); 
    dataTable.Columns.Add("Three", typeof(String)); 
    dataTable.Rows.Add("a", "b", "c"); 
    dataTable.Rows.Add("d", "e", "f"); 
    dataTable.Rows.Add("g", "h", "i"); 

    DataGridView grid = new DataGridView(); 

    grid.DataSource = dataTable; 
    int n1 = grid.Columns.Count; // returns zero 

    this.Controls.Add(grid); // why do I have to do this ? 

    grid.DataSource = null; 
    grid.DataSource = dataTable; 
    int n2 = grid.Columns.Count; // returns three 
    } 

感謝, 羅斯

+0

可能的重複[爲什麼我必須添加一個DataGridView到一個窗體以獲取數據?](http://stackoverflow.com/questions/8256762/why-must-i-add-a-datagridview-to -a-form-in-order-to-the-data) –

+0

是的......它似乎是這個問題的重複。然而,只要閱讀grid *的「Handle」屬性*(如該帖子的回答中所建議的那樣)*似乎不會影響綁定列*(在本例中)*。 –

+0

是的 - 我自己嘗試過,不能使它工作。就我個人而言,我會退後一步,重新考慮使用UI組件來處理非UI工作。是否有可能提取您的邏輯來處理數據源而不是單元集合? –

回答

3

大衛·霍爾的評論使我here,害得我尋找到電網的BindingContext中。果然,它是空的,但通過爲網格控件創建一個新的BindingContext,將網格綁定到DataTable現在填充「Columns」集合。

public Form1() 
    { 
    InitializeComponent(); 

    DataTable dataTable = new DataTable() { TableName = "Bob" }; 
     : 

    DataGridView grid = new DataGridView { Name = "Tom" }; 

    grid.BindingContext = new BindingContext(); 
    grid.DataSource = dataTable; 

    int n1 = grid.Columns.Count; // returns three 
    } 

奇怪的是,在其中設置的結合上下文或數據源中的順序似乎已經不重要了!