2016-02-14 55 views
0

我有一個DataGridView是從綁定到綁定源的DataTable填充的。我躲在通過DataTable的ColumnMapping您可以在手動添加的DataGridViewComboBox上排序DataGridView嗎?

dataTable.Columns[「ZoneId「].ColumnMapping = MappingType.Hidden; 

我已經在DataGridView的DataBindingComplete事件掛鉤,通過該行進行迭代,查找在數據綁定了zoneid列,然後設置組合框的行匹配了zoneid的方法列。

for (int i = 0; i < dataGridView.Rows.Count - 1; i++) { //Count-1 to ignore the editing row 
    // This is the DataGridView row, a subset of the backing data plus the combo and button cells 
    DataGridViewRow row = dataGridView.Rows[i]; 
    // This is the full backing data for the row 
    DataRowView dataRow = (DataRowView)row.DataBoundItem; 
    if (dataRow != null) { 
    // Find cell with comboBox by name 
    DataGridViewComboBoxCell cell = DataGridViewComboBoxCell)row.Cells["ZoneIdComboBox"]; 
    if (cell != null) { 
     Id = (string)dataRow["ZoneId"]; 
     cell.Value = Id; 
    } 
    } 
} 

ComboBox的值等於存儲在表中的隱藏列值(ID)。文本部分是該值的人類可讀描述。這些由數據庫中的單獨表格定義。另外這兩個表有一個關係,所以我的主表中的ZoneId必須在我的ComboBox表中添加一個Id。

我可以單擊任何常規綁定列的標題並對錶格進行排序。我希望能夠單擊ComboBox列並對Text條目進行排序。

回答

0

真正的解決辦法是設置AutoGenerateColumns = false。然後手動創建所有列。當最初加載DataGridView時,我會這樣做。之後,我不必再做一次。

private DataGridViewComboBoxColumn MakeDataGridViewComboBoxColumn(string fieldName, string headerText, DataGridViewColumnSortMode sortMode, bool readOnly) 
{ 
    DataGridViewComboBoxColumn result = new DataGridViewComboBoxColumn(); 
    result.Name = fieldName; 
    result.DataPropertyName = fieldName; 
    result.HeaderText = headerText; 
    result.SortMode = sortMode; 
    result.ReadOnly = readOnly; 
    return result; 
} 

然後我使用單獨的DataSource填充ComboBox列,列表或數據表。

private void QueueBindZoneColumn() 
{ 
    // The available ZoneId list may have been edited, so get a fresh copy 
    DataGridViewComboBoxColumn c = (DataGridViewComboBoxColumn)dgv1.Columns["ZoneId"]; 
    if (c != null) { 
    c.ValueType = typeof(string); 
    List<Data.Zone> ZoneList; 
    if (Data.LoadZoneId.Load(txtConnectionString.Text, out ZoneList)) { 
     c.DataSource = ZoneList; 
     c.DisplayMember = "ZoneDescription"; //List class member name to display as descriptions 
     c.ValueMember = Data.FieldNameHandling.Id; //List class member name to use as the stored value 
    } 
    } 
} 

當在DataGridView的BindingSource分配,組合框的值設置,因爲該表的字段名相匹配的組合框的DataPropertyName

偉大的事情是,這意味着我不必手動處理將數據從ComboBox更改分配到後臺存儲數據像我一樣。

它也處理數據的變化,我現在不再需要驗證ComboBoxes了。

加載數據後,我可以根據ComboBox中的值對行進行排序。我可能會重寫Sort方法來排序文本信息。

相關問題