Populate the data in a combobox on the selection of another combobox in C#

In this article I will explain you how to populate the data in combobox on the selection of another combobox.
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;
using System.Data.SqlClient;
namespace ComboboxSelection
{
    public partial class Form1 : Form
    {
        //Connection String
string con = “Data Source=(local);Initial Catalog=Northwind;Integrated Security=True”;
        public Form1()
        {
            InitializeComponent();
        }
        private voidForm1_Load(object sender, EventArgs e)
        {
           
            //populate data from database 
            string sql = “SELECT * From BikeType order by idx”;
            SqlConnection cnn = new SqlConnection(con);
            SqlDataReader rd;
            cnn.Open();
            SqlCommand cmd = new SqlCommand(sql, cnn);
            rd = cmd.ExecuteReader();
            comboBox1.Items.Clear();
            while (rd.Read())
            {
           comboBox1.Items.Add(new ItemData(Convert.ToInt32(rd[“idx”]),
           rd[“BikeType”].ToString()));
            }
            cnn.Close();
         }
       
    private void comboBox1_SelectedIndexChanged(object sender, EventArgse)
        {
           
           
    //populate the data from database on the selection of another combobox
            int Bk=((ItemData)comboBox1.SelectedItem).ID;
            
            string sql = “SELECT * From BikeName where BikeT=” + Bk  + ” “;
            SqlConnection cnn = new SqlConnection(con);
            SqlDataReader rd;
            cnn.Open();
            SqlCommand cmd = new SqlCommand(sql, cnn);
            rd = cmd.ExecuteReader();
            comboBox2.Items.Clear();
            while (rd.Read())
            {
                comboBox2.Items.Add(new ItemData(Convert.ToInt32(rd[“idx”]), rd[“BikeName”].ToString()));
            }
            cnn.Close();
         }
        public structItemData
        {
            public intID;
            public stringEmpName;
            public ItemData(int_ID, string _EMName)
            {
                ID = _ID;
                EmpName = _EMName;
            }
            public overridestring ToString()
            {
                returnthis.EmpName;
            }
        }
        }
    }


Leave a Reply

Your email address will not be published. Required fields are marked *