C# And MySQL - How To Populate DataGridView Depending On A Combobox Selected value

C# - How To Fill Data Into DataGridView Depending On A Combobox Selected value

                                                                                             

In This C# Tutorial We Will See How To  Bind Data Into A DataGridView 
Based On A Combobox Selected value In CSharp Programming Language And MySQL Database .


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:

c# filter datagridview using combobox




Share this

Related Posts

Previous
Next Post »