2011-09-28 87 views
0

在DataGridView ComboBox中選擇一個值並單擊bindingNavigator中的保存按鈕後,數據在數據庫中不會更新。用戶必須失去焦點才能更新數據。有沒有辦法解決這個問題?DataGridView ComboBox在焦點時不保存

+0

通常當你點擊按鈕它會得到重點,我認爲還有別的東西你能告訴你如何做到這一點? – V4Vendetta

回答

1

奇怪。我最近做了這件事,它像一個魅力。在我的應用程序中,當gridview處於編輯模式(Readonly false)時,並且當您選擇單元格時,它將變爲組合框,並且當您離開單元格時它將表現爲文本框。這是我做的

void dgUpdateItems_CellEnter(object sender, DataGridViewCellEventArgs e) 
{ 
    DataGridView dg = (DataGridView)sender; 
    if (e.ColumnIndex == dg.Columns["ItemCategory"].Index) 
    { 
     if (e.ColumnIndex == e.RowIndex) 
     { 
      dg[e.ColumnIndex, e.RowIndex].ReadOnly = true; 
      return; 
     } 
     DataGridViewComboBoxCell cmbCell = new DataGridViewComboBoxCell(); 
     ComboUpdate(cmbCell); 
     cmbCell.Value = ((DataGridView)sender)[e.ColumnIndex, e.RowIndex].Value.ToString(); 
     ((DataGridView)sender)[e.ColumnIndex, e.RowIndex] = cmbCell; 
    } 
} 

void dgUpdateItems_CellLeave(object sender, DataGridViewCellEventArgs e) 
{ 
    DataGridView dg = (DataGridView)sender; 
    if (e.ColumnIndex == dg.Columns["ItemCategory"].Index) 
    { 
     if (e.ColumnIndex == e.RowIndex) 
      return; 

     string str = dg[e.ColumnIndex, e.RowIndex].Value.ToString(); 
     DataGridViewComboBoxCell cmb = (DataGridViewComboBoxCell)dg[e.ColumnIndex, e.RowIndex]; 
     string val = cmb.Value.ToString(); 

     dg[e.ColumnIndex, e.RowIndex] = new DataGridViewTextBoxCell(); 
     dg[e.ColumnIndex, e.RowIndex].Value = val; 

這是我的代碼的一部分,如果不理解,讓我知道。 這是一個鏈接檢查出來。它可能有幫助。 ComboBox in DatagridView in Edit Mode

對不起,忘了告訴你最重要的事情,它甚至在它專注的時候也能奏效。 如果你正在尋找別的東西,請在我的頭上扔一塊石頭。 希望它有幫助。

0

嘗試保存這樣的前調用UpdateSource

ComboBox c = Keyboard.FocusedElement as ComboBox; 
if ((c != null) && (c.GetBindingExpression(ComboBox.TextProperty) != null)) 
    c.GetBindingExpression(ComboBox.TextProperty).UpdateSource(); 

HTH