How to stop DataGridView Combobox selection from disappearing

John Rutherford 21 Reputation points
2023-02-08T07:40:12.6766667+00:00

Hi,

I have a WinForm project in .Net Framework 4.7.2

I have a class "EntryModel" that is bound to a Bindingsource "bs4".

I have a datagridview (dgvEntries) with 5 text box columns + 1 combobox column

dgvEntries.Datasource = bs5

the 5 textbox columns have their DataPropertyName from the EntryModel properties.

The Comboboxcolumn (tcode) has values assigned as follows - tcode.Items.AddRange("AAA", "BBB", "CCC");

The combobox SelectedIndex value is use the change the Rate property of the EntryModel item.

private void DgvEntries_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            combo = e.Control as ComboBox;
            if (combo != null)
            {
                combo.SelectedIndexChanged -= new EventHandler(Combo_SelectedIndexChanged);
                combo.SelectedIndexChanged += Combo_SelectedIndexChanged;
            }
        }

        private void Combo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (combo != null)
            {
                if (combo.SelectedIndex == 0)
                {
                    EntryModel ent = (EntryModel)bs4.Current;
                    ent.Rate = 0.1m;
                }
                else
                {
                    EntryModel ent = (EntryModel)bs4.Current;
                    ent.Rate = 0m;
                }
            }
           
        }

This all works fine and the EntryModel properties are updated correctly. The problem is that the combobox selection disappears immediately after it is selected. I have traced the SelectedIndex value (for the combobox) through the above code and it is fine up until the last closing } of Combo_SelectedIndexChanged. At that point it reverts to -1.

Any help to prevent this value from disappearing is appreciated.

John

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,820 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,197 questions
{count} votes

1 answer

Sort by: Most helpful
  1. John Rutherford 21 Reputation points
    2023-02-10T05:56:32.0333333+00:00

    Hi Jack,

    I've finally cracked this problem.

    Had to reference my EntryModel entry

    then use this when I create the first line item for the bindingsource bs1

    entry = bs1.AddNew() as EntryModel;

    and then reference the "entry" in the CellValueChanged event

    entry = (EntryModel)bs1.Current;

    
    
    
    0 comments No comments