C# DataGridView – ComboBoxColumn From MySQL Database

We had looked at GataGridView combobox column earleir.We saw how to fill it with data from a simple array.Today we see how to populate our combobox column in datagridview with data from the database.We are using MySQL database in this case.

 

using MySql.Data.MySqlClient;
using System;
using System.Collections;
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;

namespace ComboColumn_DataBase
{
    public partial class Form1 : Form
    {
        //INITIALIZATIONS
        static string conString = "Server=localhost;Database=playersdb;Uid=root;Pwd=;";
        MySqlConnection con = new MySqlConnection(conString);
        DataTable dt = new DataTable();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = loadData().Tables[0];
            addCombo();
        }

        private DataSet loadData()
        {
            MySqlDataAdapter adapter = new MySqlDataAdapter();
            MySqlCommand cmd;
            DataSet ds = new DataSet();

            //SELECT STMTS
            string playerssql = "SELECT * FROM playerstb";
            string coachessql = "SELECT * FROM coachestb";

            //PLAYER TABLE
            cmd = new MySqlCommand(playerssql,con);
            adapter.SelectCommand = cmd;
            adapter.Fill(ds, "Players");

            //COACHES TABLE
            adapter.SelectCommand.CommandText = coachessql;
            adapter.Fill(ds, "Coaches");

            dt = ds.Tables[1];

            return ds;

        }

        //COMBO COLUMN
        public void addCombo()
        {
            //ADD COLUMNS
            DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
            combo.HeaderText = "Head Coach";
            combo.Name = "combo";

            ArrayList row = new ArrayList();

            //FILL ARRAYLIST FROM DATATABLE
            foreach(DataRow dr in dt.Rows)
            {
                row.Add(dr["Name"].ToString());
            }
            //ADD TO COMBO
            combo.Items.AddRange(row.ToArray());

            //ADD THE COMBO TO DATAGRIDVIEW
            dataGridView1.Columns.Add(combo);

        }

    }
}

Cheers.

Related Posts

Leave a Reply

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