C# DataGridView and combobox binding

T.Zacks 3,986 Reputation points
2021-11-04T07:20:58.96+00:00

Suppose i have a datagridview and one column type is DataGridViewComboBoxColumn. i want when user will select anything from combo box then GenderID will be attached to that tag property of that cell where combo box appear. as a result when i will read values in loop then i can read selected GenderID choose by user. so how to store selected GenderID in the tag property of the cell when user select or change value from combo box ?

please help me with code. thanks

i am also curious that if i do not store GenderID in tag property of cell and when i will read values from each cell of each rows in loop then can i get selected GenderID from DataGridViewComboBoxColumn whatever user selected ?

please help me with concept & code sample. thanks

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,229 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,031 Reputation points
    2021-11-08T18:04:31.637+00:00

    how can i get selected value instead of selected text and assign that value to that cell where combo box appear

    If you need the value and even the underlying key use EditingControlShowing event, cast DataGridViewComboBoxEditingControl.SelectedItem to the proper type then access the value. Lets say we are dealing with a DataTable then to get the underlying key int colorId = ((DataRowView)(((DataGridViewComboBoxEditingControl)sender).SelectedItem)).Row.Field<int>("ColorId");

    If you don't need the value ASAP then cast the BindingSource.Current to (keeping with above) to a DataRow (first we cast to a DataRowView) then access the field.

    If not dealing with a DataTable then cast to the class type and go from there.

    Now with that said, the majority of developers simply have no clue on how to a) properly setup a DataGridViewComboBox b) know the events to use. Once those two items are clear it's simple to work with changing data.


2 additional answers

Sort by: Most helpful
  1. Karen Payne MVP 35,031 Reputation points
    2021-11-04T10:00:36.727+00:00

    Assuming this is Windows Forms as there is no DataGridView for WPF, instead a DataGrid.

    The best way to start off with is to have in your case a container such as a DataTable that has GenerId column (not to be displayed) and a DataGridViewComboBoxColumn with the DataSource set to the text for gender.

    Setup each column in the DataGridView using the designer for the control. Set AutoGenerateColumns for the DataGridView to false since you have created columns in the designer.

    Main data in this case is stored in a DataTable assigned to BindingSource then becomes the DataSource for the DataGridView, similarly this is done for the DataGridViewComboBoxColumn.

    How to get current values? Cast the main BindingSource.Current to a DataRowView which allows access to the DataRow representing the data.

    Comments: At this point many newer developers will ask, is there an easier way? No.
    What about a DataGridView without a DataSource? Sure this can be done but messy.

    In the following GitHub repository the code is setup purely to demonstrate the above, in this case there are two DataGridViewColumns. I get data from SQL-Server but can work say by read csv or json files etc.

    Tip Go to the repository, type a period character and the code will display in Visual Studio Code online.

    Yellow highlight denotes Combobox columns

    146486-datagridviewcombo.png


  2. AgaveJoe 26,191 Reputation points
    2021-11-08T19:39:09.48+00:00

    The ComboBox contains a list of objects. It is up to you to design the list of objects which can be an array of strings or a collection of complex types. The following example populates a ComboBox with a collection of complex types. The ValueMember defines what test is shown in the UI. The complex type's Id property value is assigned to a label when the selected index changes.

    public partial class Form1 : Form  
    {  
        public class ComboBoxData  
        {  
            public int Id { get; set; }  
            public string Text { get; set; }  
        }  
      
        public Form1()  
        {  
            InitializeComponent();  
      
            comboBox1.DataSource = PopulateComboBoxData();  
            comboBox1.ValueMember = "Text";  
        }  
      
        private List<ComboBoxData> PopulateComboBoxData()  
        {  
            return new List<ComboBoxData>()  
            {  
                new ComboBoxData()  
                {  
                    Id = 1,  
                    Text = "Optiopn 1"  
                },  
                new ComboBoxData()  
                {  
                    Id = 2,  
                    Text = "Optiopn 2"  
                },  
                new ComboBoxData()  
                {  
                    Id = 3,  
                    Text = "Optiopn 3"  
                }  
            };  
        }  
      
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)  
        {  
            var item = (ComboBoxData)((ComboBox)sender).SelectedItem;  
            label1.Text = $"{item.Id}";  
        }  
    }  
    

    The ComboBox reference documentation is a great place to learn how the ComboBox works.

    Keep in mind, it is very difficult to answer technical questions without source code that illustrates the problem. In the future, I recommend creating simple tests like the code above rather trying to do too much at one time. In this case, I thing you need to learn the ComboBox control first.