Search code examples
c#.netwinformsdatagridviewdatagridcomboboxcolumn

Change DatagridviewTextBox Text When DatagridviewComboBox Selected Index Changes


In My DatagridView,I Have Two Columns, ComboxboxColumn and TextboxColumn. I want to change the value of textbox when combobox selected index changes (in general combobox it has selected index change event but datagridviewComboBox does not have it)


Solution

  • Give these two simple methods a go (the '1' in the top method is the index of the combobox column)

    The line that you would make you modifications to would be the setter line cel.Value =, as you may change it to whatever you like.


        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (dataGridView1.CurrentCell.ColumnIndex == 1 && e.Control is ComboBox)
            {
                ComboBox comboBox = e.Control as ComboBox;
                comboBox.SelectedIndexChanged += LastColumnComboSelectionChanged;
            }
        }
    
        private void LastColumnComboSelectionChanged(object sender, EventArgs e)
        {
            var currentcell = dataGridView1.CurrentCellAddress;
            var sendingCB = sender as DataGridViewComboBoxEditingControl;
            DataGridViewTextBoxCell cel = (DataGridViewTextBoxCell)dataGridView1.Rows[currentcell.Y].Cells[0];
            cel.Value = sendingCB.EditingControlFormattedValue.ToString();
        }
    

    enter image description here