Click here to Skip to main content
15,901,035 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have DataGridView which contains two ComboBox columns. I want that The second ComboBox will be filled with data depending on the selected value from first ComboBox.

Below is my code.

Thank you

-Tushar

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace t1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            logicload(2, 2);
        }
        public void logicload(int row, int col)
        {

            dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
            for (int i = 1; i <= col; i++)
            {
                dataGridView1.Columns.Add("Col" + i, "Stage" + i);
            }

            dataGridView1.Rows.Add(row);

            //make row 1 at all columns into combobox cell.
            dataGridView1.Rows[0].Cells[1] = new DataGridViewComboBoxCell();
            dataGridView1.Rows[1].Cells[1] = new DataGridViewComboBoxCell();
            dataGridView1.Rows[0].Cells[0].Value = "Country";
            dataGridView1.Rows[1].Cells[0].Value = "City";

            loadComboboxesSampleItems();
        }
        DataGridViewComboBoxCell CellColumn1, CellColumn2;
        private void loadComboboxesSampleItems()
        {

            CellColumn1 = (DataGridViewComboBoxCell)this.dataGridView1.Rows[0].Cells[1];
             CellColumn2 = (DataGridViewComboBoxCell)this.dataGridView1.Rows[1].Cells[1];
            var list1 = new List<string>() { "IND", "PAK", "AUS", "USA" };
           // var list2 = new List<string>() { "AGRA", "DEHLI", "KANPUR" };
            var list3 = new List<string>() { "MOhali" };

            CellColumn1.DataSource = list1;// CellColumn2.DataSource = list2;

        }

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


        }
        private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
             var list2 = new List<string>() { "AGRA", "DEHLI", "KANPUR" };
            if (CellColumn1.Selected.Equals(true))
            {
                ComboBox cb = (ComboBox)sender;
                string item = cb.Text;
                if (item != null)
                {
                    if (cb.SelectedIndex.Equals(0))
                    {
                        //MessageBox.Show(item);
                        CellColumn2.DataSource = list2;

                    }
                }
            }
           
        }
    }
}
Posted
Updated 22-May-14 2:43am
v3
Comments
Richard MacCutchan 22-May-14 4:34am    
OK, so what is your question?
TusharZoo 22-May-14 5:27am    
how to fill the items of a combobox by selecting the item of another combobox when both combobox are on datagridview c#

suppose we have two combobox one have country name and other have city name

when we select one country name the cities of those country should show on another combobox
Richard MacCutchan 22-May-14 5:36am    
OK, so when the item in the first combobox is selected (i.e. in your selection event) you need to populate the second with the items in question. What exactly is your problem?
TusharZoo 22-May-14 6:00am    
Actually i am new in c# and i want the simple code for it
(the two combobox should in datagridview (DataGridviewComboBoxCell) and when the item in the first combobox is selected i need to populate the second combobox with items )

Richard MacCutchan 22-May-14 6:07am    
You already have the code that adds your list of countries to the first ComboBox. Add an event handler to that which will read the selected item, and use that to add the appropriate city list to the second CombBox.

1 solution


  1. Your for statement


        for (int i = 1; i <= col; i++)


    uses an unexpected initial value and an unexpected condition test. I would have expected


        for ( int i = 0; ( i < col ); i++).


    In C#, arrays indices start at 0.




  2. The fragment


        "Col" + i, "Stage" + i


    is a sign of lazy programming. "i" is not a string and should not be used that way. You should have used


        "Col" + i.ToString ( ), "Stage" + i.ToString ( )




  3. CellColumn1.Selected is a boolean. It returns true or false. So your if statement


        if ( CellColumn1.Selected.Equals ( true ) )


    should read


        if ( CellColumn1.Selected )




  4. Your if statement


        if ( item != null )


    should read


        if ( !String.IsNullOrEmpty ( item ) )




  5. Your if statement


        if ( combo_box.SelectedIndex.Equals ( 0 ) )


    should read


        if ( combo_box.SelectedIndex == 0 )




  6. You did not include data for the chosen country


Working example follows.


C#
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace DataGridViewComboBoxes
    {

    // *************************************************** class Form1

    public partial class Form1 : Form
        {

        // *************************************** enums and constants

        enum ControlTypes
            {
            COMBO,
            TEXT
            }

        const int                   CITIES_ROW = 1;
        const int                   CITIES_CELL = 1;
        const int                   COUNTRIES_ROW = 0;
        const int                   COUNTRIES_CELL = 1;

        const int                   NUMBER_COLUMNS = 2;
        const int                   NUMBER_ROWS = 2;

        // ************************************************* variables

        List < string >             Australian_cities = 
                                        new List < string > ( ) { 
                                            "Sydney", 
                                            "Melbourne", 
                                            "Brisbane", 
                                            "Perth", 
                                            "Adelaide" };
        DataGridViewComboBoxCell    countries_cell;
        DataGridViewComboBoxCell    cities_cell;
        List < string >             cities;
        List < string >             Indian_cities = 
                                        new List < string > ( ) { 
                                            "Mumbai", 
                                            "Delhi", 
                                            "Bangalore", 
                                            "Karnataka", 
                                            "Hyderabad" };
        List < string >             Pakistani_cities = 
                                        new List < string > ( ) { 
                                            "Karachi", 
                                            "Lahore", 
                                            "Faisalabad", 
                                            "Rawalpindi", 
                                            "Punjab" };
         List < string >             USA_cities = 
                                        new List < string > ( ) { 
                                            "New York", 
                                            "Los Angeles", 
                                            "Chicago", 
                                            "Houston", 
                                            "Philadelphia" };
        List < string >             countries = 
                                        new List < string > ( ) { 
                                            "IND", 
                                            "PAK", 
                                            "AUS", 
                                            "USA" };

        // ***************************************************** Form1

        public Form1 ( )
            {
            InitializeComponent ( );

            initialize_datagridview ( NUMBER_ROWS, NUMBER_COLUMNS );
            load_sample_data ( );

            dataGridView1.DataError += 
                new DataGridViewDataErrorEventHandler ( 
                    dataGridView1_DataError );
            }

        // *********************************** dataGridView1_DataError

        void dataGridView1_DataError ( 
                                object                         sender, 
                                DataGridViewDataErrorEventArgs e )
            {

            }

        // *********************************** initialize_datagridview

        void initialize_datagridview ( int rows, 
                                       int columns )
            {

            dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;

            for ( int i = 0; ( i < columns ); i++ )
                {
                string i_plus_one = ( i + 1 ).ToString ( );

                dataGridView1.Columns.Add ( "Col" + i_plus_one, 
                                            "Stage" + i_plus_one );
                }

            dataGridView1.Rows.Add ( rows );
                                        // make first row columns into 
                                        // DataGridViewComboBoxCell
            dataGridView1.Rows [ 0 ].Cells [ 1 ] = 
                                    new DataGridViewComboBoxCell ( );
            dataGridView1.Rows [ 1 ].Cells [ 1 ] = 
                                    new DataGridViewComboBoxCell ( );

            dataGridView1.Rows [ 0 ].Cells [ 0 ].Value = "Country";
            dataGridView1.Rows [ 1 ].Cells [ 0 ].Value = "City";

            dataGridView1.EditingControlShowing +=
                new DataGridViewEditingControlShowingEventHandler (
                    dataGridView1_EditingControlShowing );
            }

        // ****************************************** load_sample_data

        private void load_sample_data ( )
            {

            countries_cell = ( DataGridViewComboBoxCell ) 
                                dataGridView1.Rows [ COUNTRIES_ROW ].
                                              Cells [ COUNTRIES_CELL ];
            cities_cell = ( DataGridViewComboBoxCell ) 
                                dataGridView1.Rows [ CITIES_ROW ].
                                              Cells [ CITIES_CELL ];
            countries_cell.DataSource = null;
            countries_cell.DataSource = countries;
            }

        // *********************** dataGridView1_EditingControlShowing

        void dataGridView1_EditingControlShowing ( 
                    object                                     sender, 
                    DataGridViewEditingControlShowingEventArgs e )
            {
            ControlTypes    control_type;
            Object          editing_control;

            try
                {
                editing_control = 
                    ( DataGridViewTextBoxEditingControl ) e.Control;
                control_type = ControlTypes.TEXT;
                }
            catch
                {
                editing_control = 
                    ( DataGridViewComboBoxEditingControl ) e.Control;
                control_type = ControlTypes.COMBO;
                }

            if ( control_type == ControlTypes.COMBO )
                {
                ComboBox  combo_box = ( ComboBox ) editing_control;

                if ( combo_box != null )
                    {
                    combo_box.TextChanged -= 
                        new EventHandler ( 
                            editingcontrol_TextChanged );
                    combo_box.TextChanged += 
                        new EventHandler ( 
                            editingcontrol_TextChanged );
                    }
                }
            }

        // ******************************** editingcontrol_TextChanged

        void editingcontrol_TextChanged ( object    sender, 
                                             EventArgs e )
            {

            if ( countries_cell.Selected )
                {
                ComboBox    combo_box = ( ComboBox ) sender;
                string      text = combo_box.Text;

                if ( !String.IsNullOrEmpty ( text ) )
                    {
                    switch ( text )
                        {
                        case "IND":
                            cities = Indian_cities;
                            break;

                        case "PAK":
                            cities = Pakistani_cities;
                            break;

                        case "AUS":
                            cities = Australian_cities;
                            break;

                        case "USA":
                            cities = USA_cities;
                            break;

                        default:
                            throw new ApplicationException ( 
                                "Unrecognized country" );
                        }
                                        // avoid DataError by rebuild
                                        // of cities_cell
                    cities_cell.Dispose ( );
                    cities_cell = ( DataGridViewComboBoxCell ) 
                                        dataGridView1.
                                            Rows [ CITIES_ROW ].
                                            Cells [ CITIES_CELL ];
                    combo_box.TextChanged -= 
                        new EventHandler ( 
                            editingcontrol_TextChanged );
                    combo_box.TextChanged += 
                        new EventHandler ( 
                            editingcontrol_TextChanged );

                    cities_cell.DataSource = null;
                    cities_cell.DataSource = cities;
                    }
                }
            }

        } // class Form1

    } // namespace DataGridViewComboBoxes


Hope that helps.

 
Share this answer
 
Comments
Richard MacCutchan 23-May-14 4:33am    
Excellent solution; I guess the key to this is knowing which events to handle - which I didn't.
gggustafson 28-May-14 14:57pm    
Just FYI, one of the reasons that I'm willing to put effort into answering questions is the breadth and depth of research needed to answer the question. I view most OPs as colleagues and their questions give me the chance to improve my personal understanding. This question required about six hours to answer - time well spent.
Richard MacCutchan 29-May-14 3:21am    
I agree entirely, although I don't always have that much time to spend on a problem. However, I do sometimes go back to an issue at a later time if it is still unanswered, and work on it further.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900