C# And MySQL - Populate Combobox Depending On Another Combobox Selected Value

C# And MySQL - Bind Combobox Depending On Another Combobox Selected Value

                                                                                             

In This C# Tutorial We Will See How To  Fill Data Into A ComboBox
Based On A ComboBox Selected value In CSharp Programming Language .


Source Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace Csharp_And_MySQL
{
    public partial class Csharp_MySQL_datagridview_depending_combobox_value : Form
    {
        MySqlConnection con = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog ='project';username=root;password=");
        MySqlCommand command;
        MySqlDataAdapter adapter;
        DataTable table;

        public Csharp_MySQL_datagridview_depending_combobox_value()
        {
            InitializeComponent();
        }

        private void Csharp_MySQL_datagridview_depending_combobox_value_Load(object sender, EventArgs e)
        {
            string query = "SELECT `CAT_ID`, `CAT_NAME` FROM `categories`";
            comboBox_Categories.DataSource = getData(query);
            comboBox_Categories.DisplayMember = "CAT_NAME";
            comboBox_Categories.ValueMember = "CAT_ID";

            comboBox_Categories_SelectedIndexChanged(null, null);
        }

        public DataTable getData(string query)
        {
            command = new MySqlCommand(query, con);
            adapter = new MySqlDataAdapter(command);
            table = new DataTable();
            adapter.Fill(table);
            return table;
        }

        private void comboBox_Categories_SelectedIndexChanged(object sender, EventArgs e)
        {
            int val;
            Int32.TryParse(comboBox_Categories.SelectedValue.ToString(), out val);
            string query = "SELECT `ID_PRO`, `PRO_NAME`, `QTE_IN_STOCK`, `PRICE`, `ID_CAT` FROM `products` WHERE `ID_CAT` = " + val;
            dataGridView_Products.DataSource = getData(query);
        }
    }
}

=> OUTPUT:

Populate Combobox Depending On Another Combobox In C#




Share this

Related Posts

Previous
Next Post »

1 comments:

comments
29 mars 2016 à 11:07 delete

populate 3 combobox combobox2 depend on combobox1 and combobox3 depend on combobox2

Reply
avatar