2011-07-16 42 views
1

我對C#還是有點新,但我使用的Winforms,我有一個DataGridView連接到數據源,並正在填充正確。如何更改動態添加的DataGridViewComboBoxColumn的組合框單元格的文本?

我也在運行時添加了一個ComboBoxColumn。這個ComboBoxColumn被連接到一個數據源,displaymember和valuemember被設置,headertext被設置,然後列被添加到數據網格中。連接工作得很好,當用戶單擊組合框時按預期填充。

當用戶在網格中完成一個新行時,他顯然會選擇comboBox中的項目,然後在完成時將整行更新到我的數據庫。

我的問題是:當這個數據網格再次打開或重新繪製它由於datasource屬性填充,但我怎麼讓comboBox單元格顯示他最初選擇的VALUE,而不是一個空白框。我知道從數據庫中獲取價值並輸入價值的代碼。理想情況是,如果我可以將該變量放在comboBox的顯示中。請記住,comboBox仍然是數據綁定的,以便用戶可以編輯該值,如果他願意的話?

我知道在一個普通的comboBox控件中,我應該設置.Text屬性。但DataGridViewComboBox不具有相同的屬性。

下面是實際的數據連接的代碼並添加comboBoxColumn的:

public void AddComboBoxColumn(DataGridView datagridName, DataTable table, string headerText, int columnIndex) 
    { 
     DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn(); 

     GetDisplayAndValueMembers(table, headerText); //Calls method that gets the datasource, displaymember, valuemember depending on column 

     column.DataSource = tableRef; //sets datasource to table referenced by column 
     column.DisplayMember = displayMember; //sets displaymember 
     column.ValueMember = valueMember; //sets valuemember 

     column.HeaderText = headerText; //changes headertext to displayed text 

     if (newColumnIndex == 0) 
      datagridName.Columns.Add(column); //added to end of datagrid 
     else 
     { 
      datagridName.Columns.RemoveAt(columnIndex); 
      datagridName.Columns.Insert(newColumnIndex, column); //added in specific index if needed 
     } 
    } 

這只是顯示下拉的dataconnection。顯然有很多方法正在使用大量的代碼。但這不是問題,因爲這工作正常。我不知道如何去實際顯示以前選擇的項目作爲組合框的文本的問題?

+1

也許提高你的問題來顯示相關的代碼? –

回答

1

這聽起來像你正在尋找的是ComboBoxColumnDataPropertyName財產。此屬性創建DataGridViewDataSourceComboBoxColumn的選定值之間的綁定。

例如,假設您有一個顯示在組合框中的產品列表。然後,您將在您的DataGridViewDataSource中有一個ProductId。事情是這樣的:

// There Orders is a data table coming from the db which includes the product id column 
dataGridView1.DataSource = Orders; 

// You set up your column just the same, with the DisplayMember and ValueMember 
DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();   
GetDisplayAndValueMembers(table, headerText); 
column.DataSource = tableRef; //sets datasource to table referenced by column 
column.DisplayMember = displayMember; //sets displaymember 
column.ValueMember = valueMember; //sets valuemember  
column.HeaderText = headerText; //changes headertext to displayed text 

//Now you also set the DataPropertyName 
column.DataPropertyName = "ProductId"; // this is the name of a column or property from the grid datasource 

dataGridView1.Columns.Add(column); 

隨着DataPropertyName集你現在將有ComboBoxColumnDataGridView之間的數據綁定。

如果您的基礎數據源絕對不能具有組合框屬性的值,那麼您需要在自定義代碼中處理所有此ComboBoxColumn的保存和值設置。

要設置DataGridViewComboBoxCell的所選值,請選擇該單元格,然後設置它的Value屬性。

dataGridView1.Rows["rowname"].Cells["columnname"].Value = valueFromDb; 
+0

這工作完美! column.DataPropertyName完全解決了它。我不必添加dataGridView.Value語句。非常感謝大衛。 –

相關問題