Cascading ComboBox inside DataGridView in Windows Application

Last Reply 4 months ago By dharmendr

Posted 4 months ago

when i am selecting india from combobox country,selected region is displaying asia.

what i want is : after getting the result of combobox selection india,combobox region should be disabled with asia into it. User should not be able to change region asia to any other region. OR ELSE if user try to select some other region,validation messagebox should be shown.

https://ibb.co/dTt75p

        private void ManualEntryForm1_Load(object sender, EventArgs e)
        {                    
            displayCmbRegions();
            displayCmbCountries();          
        }

 

        private void displayCmbCountries()
        {
            SqlConnection conn = null;
            try
            {
                MyConnect myCnn = new MyConnect();  
                String connString = myCnn.getConnect().ToString();


             
                
                SqlCommand command;
                DataSet ds;
                conn = new SqlConnection(connString);
                ds = new DataSet();
                command = new SqlCommand();


                conn.Open();
                command.Connection = conn;

                command.CommandType = CommandType.StoredProcedure;

                command.CommandText = "AllCurrCountries";

                SqlDataReader reader = command.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(reader);

                cmbCountry.DataSource = dt;
                cmbCountry.ValueMember = "ID";
                cmbCountry.DisplayMember = "countryname";
             //   if (cmbCountry.DisplayMember == "countryname")
                 //   cmbRegion.Enabled = false;
               // else
                 //   cmbRegion.Enabled = true;
                conn.Close();

               
            }
            catch (Exception e)
            {
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }

 

        private void displayCmbRegions()
        {
            SqlConnection conn = null;
            try
            {
                MyConnect myCnn = new MyConnect();  
                String connString = myCnn.getConnect().ToString();

               
                
                SqlCommand command;
               
                conn = new SqlConnection(connString);
             
                command = new SqlCommand();


                conn.Open();
                command.Connection = conn;

                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "AllCurrRegions";

                SqlDataReader reader = command.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(reader);

                cmbRegion.DataPropertyName = "Region";
                cmbRegion.Name = "EditRegion";
                cmbRegion.DataSource = dt;
                cmbRegion.ValueMember = "ID";
                cmbRegion.DisplayMember = "regionname";

                conn.Close();
              
                
            }
            catch (Exception e)
            {
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }

 

        private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {            
                try
                {
                    int column=excelGridview.CurrentCell.ColumnIndex;
                    int row = excelGridview.CurrentCell.RowIndex;
                    int country = Convert.ToInt32(((ComboBox)sender).SelectedValue);

                    if (column == 7)
                    {
                        MyConnect myCnn = new MyConnect();   
                        String connString = myCnn.getConnect().ToString();


                        SqlConnection conn;
                        SqlCommand command;
                        conn = new SqlConnection(connString);
                        command = new SqlCommand();

                       
                        if (country > 0)
                        {
                            try
                            {
                                conn.Open();

                                string query = "select regionID FROM  countryinfo country  WHERE country.ID=" + country + "";

                                command = new SqlCommand(query, conn);

                                SqlDataReader reader = command.ExecuteReader();
                                DataTable dt = new DataTable();
                                dt.Load(reader);

                                var currentcell = excelGridview.CurrentCellAddress;
                                DataGridViewComboBoxCell cel = (DataGridViewComboBoxCell)excelGridview.Rows[currentcell.Y].Cells[8];

                                cel.Value = Convert.ToInt64(dt.Rows[0]["regionID"]);
                                
                                conn.Close();

                            }
                            catch (Exception ex1)
                            {
                            }
                            finally
                            {
                                if (conn != null)
                                {
                                    conn.Close();
                                }
                            }
                        }
                    }
                }
                catch (Exception) { }            
        }
Posted 4 months ago

Hi chetan,

Refer below example.

C#

private List<Country> countries;
private List<State> states;
private ComboBox cmbCountry;
private ComboBox cmbState;

public Form1()
{
    InitializeComponent();
    countries = GetCountries();
    states = GetStates();
    BindDataGridView();
}

private List<Country> GetCountries()
{
    var countryList = new List<Country>
                    {
                        new Country {Id=1,Name = "USA"},
                        new Country {Id=2,Name = "India"},
                        new Country {Id=3,Name = "Canada"}
                    };

    return countryList;
}
private List<State> GetStates()
{
    var states = new List<State>();
    states.Add(new State { Id = 1, Name = "Alabama" });
    states.Add(new State { Id = 2, Name = "Arizona" });
    states.Add(new State { Id = 3, Name = "Alaska" });
    states.Add(new State { Id = 4, Name = "Maharashtra" });
    states.Add(new State { Id = 5, Name = "Gujarat" });
    states.Add(new State { Id = 6, Name = "Goa" });
    states.Add(new State { Id = 7, Name = "Ontario" });
    states.Add(new State { Id = 8, Name = "Quebec" });
    states.Add(new State { Id = 9, Name = "Manitoba" });

    return states;
}
private List<State> GetStatesBasedOnCountry(string country)
{
    var states = new List<State>();
    if (country == "1")
    {
        states.Add(new State { Id = 1, Name = "Alabama" });
        states.Add(new State { Id = 2, Name = "Arizona" });
        states.Add(new State { Id = 3, Name = "Alaska" });
    }
    if (country == "2")
    {
        states.Add(new State { Id = 4, Name = "Maharashtra" });
        states.Add(new State { Id = 5, Name = "Gujarat" });
        states.Add(new State { Id = 6, Name = "Goa" });
    }
    if (country == "3")
    {
        states.Add(new State { Id = 7, Name = "Ontario" });
        states.Add(new State { Id = 8, Name = "Quebec" });
        states.Add(new State { Id = 9, Name = "Manitoba" });
    }

    return states;
}

private void BindDataGridView()
{
    dataGridView1.CellLeave += dataGridView1_CellLeave;
    dataGridView1.EditingControlShowing += dataGridView1_EditingControlShowing;

    DataGridViewTextBoxColumn customer = new DataGridViewTextBoxColumn();
    customer.Name = "Customer";
    customer.HeaderText = "Name";

    DataGridViewComboBoxColumn country = new DataGridViewComboBoxColumn();
    country.Name = "Country";
    country.HeaderText = "Country";

    DataGridViewComboBoxColumn state = new DataGridViewComboBoxColumn();
    state.Name = "State";
    state.HeaderText = "State";

    dataGridView1.Columns.Add(customer);
    dataGridView1.Columns.Add(country);
    dataGridView1.Columns.Add(state);

    ((DataGridViewComboBoxColumn)dataGridView1.Columns["Country"]).DisplayMember = "Name";
    ((DataGridViewComboBoxColumn)dataGridView1.Columns["Country"]).ValueMember = "Id";
    ((DataGridViewComboBoxColumn)dataGridView1.Columns["Country"]).DataSource = countries;

    ((DataGridViewComboBoxColumn)dataGridView1.Columns["State"]).DisplayMember = "Name";
    ((DataGridViewComboBoxColumn)dataGridView1.Columns["State"]).ValueMember = "Id";
    ((DataGridViewComboBoxColumn)dataGridView1.Columns["State"]).DataSource = states;

    dataGridView1.Rows.Add("John Hammond");
    dataGridView1.Rows.Add("Mudassar Khan");
    dataGridView1.Rows.Add("Robert Schidner");
}

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (dataGridView1.CurrentRow != null && dataGridView1.CurrentCell.ColumnIndex == 2)
    {
        cmbState = e.Control as ComboBox;
        if (cmbState != null)
        {
            //cmbState.DropDown += cmbState_DropDown;
            cmbState.DataSource = null;
            string countryName = dataGridView1.CurrentRow.Cells[1].Value.ToString();
            List<State> stateList = new List<State>();
            stateList = GetStatesBasedOnCountry(countryName);
            foreach (State item in stateList)
            {
                cmbState.Items.Add(item.Name);
            }
        }
    }

    if (dataGridView1.CurrentRow != null && dataGridView1.CurrentCell.ColumnIndex == 1)
    {
        cmbCountry = e.Control as ComboBox;
        if (cmbCountry != null)
        {
            cmbCountry.SelectedValueChanged += cmbCountry_SelectedValueChanged;
        }
    }
}

void cmbCountry_SelectedValueChanged(object sender, EventArgs e)
{
    //If category value changed then reset item to default.
    //dataGridView1.CurrentRow.Cells[2].Value = 0;
}

void cmbState_DropDown(object sender, EventArgs e)
{
            
}

private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
    if (cmbState != null)
    {
        cmbState.DropDown -= cmbState_DropDown;
    }
    if (cmbCountry != null)
    {
        cmbCountry.SelectedValueChanged -= cmbCountry_SelectedValueChanged;
    }
}

public class Country
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class State
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Screenshot