开发者

DataGridView ComboBox doesn't save when focus

After select a value in DataG开发者_开发技巧ridView ComboBox and click a save button in bindingnavigator, data doesn't get update in database. User must lose focus in order to get the data updated. Is there a way to fix this problem ?


Weird. I have done this recently and it worked like a charm. In my application when the gridview is in Edit mode (Readonly false), and when you select the cell, it will become combobox and when you leave the cell it will behave as textbox. Here is what I did

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;

It is some part of my code if not understanding, let me know. Here is a link check it out. It may help. ComboBox in DatagridView in Edit Mode

And sorry, forgot to tell you most important thing, it worked even when it is focused. And if you are looking for something else, please throw a stone on my head. Hope it helps.


Try calling UpdateSource before saving like this:

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

HTH

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜