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
}
感謝, 羅斯
可能的重複[爲什麼我必須添加一個DataGridView到一個窗體以獲取數據?](http://stackoverflow.com/questions/8256762/why-must-i-add-a-datagridview-to -a-form-in-order-to-the-data) –
是的......它似乎是這個問題的重複。然而,只要閱讀grid *的「Handle」屬性*(如該帖子的回答中所建議的那樣)*似乎不會影響綁定列*(在本例中)*。 –
是的 - 我自己嘗試過,不能使它工作。就我個人而言,我會退後一步,重新考慮使用UI組件來處理非UI工作。是否有可能提取您的邏輯來處理數據源而不是單元集合? –