Introduction

In this article, we will learn how to load datagridview from a database in C#. C# datagridview loads data from a MySQL database. This tutorial takes a specific table from a database and displays it on a DataGridView. This is done with a DataReader and data logic. A visual representation of data is the end result.
Let’s follow the steps to learn how to load data in Datagridview/
  1. Create a database in MySQL with name “test” and create a table with the name “user”, like shown below.
Load Datagridview From Database In C#
  1. Create a new application project. In Visual Studio, on the menu click File> New > Project. For more details, see the following menu on the display.
Load Datagridview From Database In C#
  1. Then a window will open called New Project that should look like below:
Load Datagridview From Database In C#
  1. Write down the name of the project that will be created on a field Name. Specify the directory storage project by accessing the field Location. Next, give the name of the solution in the Solution Name. Then click OK.

Load Datagridview From Database In C#

  1. Create a new windows form like the one shown below.
Load Datagridview From Database In C#
Create a new class for the connection database and write the following program listing:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using MySql.Data.MySqlClient;
  6. using System.Windows.Forms;
  7. using System.Data;
  8. namespace DataGridview_Connect_DB
  9. {
  10. class ConnectionDB
  11. {
  12. MySql.Data.MySqlClient.MySqlConnection conn;
  13. string myConnectionString;
  14. static string host = "localhost";
  15. static string database = "test";
  16. static string userDB = "camellab";
  17. static string password = "camellab";
  18. public static string strProvider = "server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;
  19. public bool Open()
  20. {
  21. try
  22. {
  23. strProvider = "server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;
  24. conn = new MySqlConnection(strProvider);
  25. conn.Open();
  26. return true;
  27. }
  28. catch (Exception er)
  29. {
  30. MessageBox.Show("Connection Error ! " + er.Message, "Information");
  31. }
  32. return false;
  33. }
  34. public void Close()
  35. {
  36. conn.Close();
  37. conn.Dispose();
  38. }
  39. public DataSet ExecuteDataSet(string sql)
  40. {
  41. try
  42. {
  43. DataSet ds = new DataSet();
  44. MySqlDataAdapter da = new MySqlDataAdapter(sql, conn);
  45. da.Fill(ds, "result");
  46. return ds;
  47. }
  48. catch (Exception ex)
  49. {
  50. MessageBox.Show(ex.Message);
  51. }
  52. return null;
  53. }
  54. public MySqlDataReader ExecuteReader(string sql)
  55. {
  56. try
  57. {
  58. MySqlDataReader reader;
  59. MySqlCommand cmd = new MySqlCommand(sql, conn);
  60. reader = cmd.ExecuteReader();
  61. return reader;
  62. }
  63. catch (Exception ex)
  64. {
  65. MessageBox.Show(ex.Message);
  66. }
  67. return null;
  68. }
  69. public int ExecuteNonQuery(string sql)
  70. {
  71. try
  72. {
  73. int affected;
  74. MySqlTransaction mytransaction = conn.BeginTransaction();
  75. MySqlCommand cmd = conn.CreateCommand();
  76. cmd.CommandText = sql;
  77. affected = cmd.ExecuteNonQuery();
  78. mytransaction.Commit();
  79. return affected;
  80. }
  81. catch (Exception ex)
  82. {
  83. MessageBox.Show(ex.Message);
  84. }
  85. return -1;
  86. }
  87. }
  88. }

Next step, Back to windows form and view code to write the following program listing,
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using MySql.Data.MySqlClient;
  10. using System.Collections;
  11. namespace DataGridview_Connect_DB
  12. {
  13. public partial class Form1 : Form
  14. {
  15. ConnectionDB con = new ConnectionDB();
  16. //arraylist to getter and setter data
  17. private static ArrayList ListID = new ArrayList();
  18. private static ArrayList ListFirstname = new ArrayList();
  19. private static ArrayList ListLastname = new ArrayList();
  20. private static ArrayList ListTelephone = new ArrayList();
  21. private static ArrayList ListAddress = new ArrayList();
  22. public Form1()
  23. {
  24. InitializeComponent();
  25. }
  26. private void button1_Click(object sender, EventArgs e)
  27. {
  28. GetData();
  29. if (ListID.Count > 0)
  30. {
  31. updateDatagrid();
  32. }
  33. else
  34. {
  35. MessageBox.Show("Data not found");
  36. }
  37. }
  38. private void GetData()
  39. {
  40. try
  41. {
  42. con.Open();
  43. string query = "select id,firstname,lastname,telephone,address from user";
  44. //MySqlDataReader row;
  45. MySqlDataReader row;
  46. row = con.ExecuteReader(query);
  47. if (row.HasRows)
  48. {
  49. while (row.Read())
  50. {
  51. ListID.Add(row["id"].ToString());
  52. ListFirstname.Add(row["firstname"].ToString());
  53. ListLastname.Add(row["lastname"].ToString());
  54. ListTelephone.Add(row["telephone"].ToString());
  55. ListAddress.Add(row["address"].ToString());
  56. }
  57. }
  58. else
  59. {
  60. MessageBox.Show("Data not found");
  61. }
  62. con.Close();
  63. }
  64. catch (Exception err)
  65. {
  66. MessageBox.Show(err.ToString());
  67. }
  68. }
  69. private void updateDatagrid()
  70. {
  71. dataGridView1.Rows.Clear();
  72. for (int i = 0; i < ListID.Count; i++)
  73. {
  74. DataGridViewRow newRow = new DataGridViewRow();
  75. newRow.CreateCells(dataGridView1);
  76. newRow.Cells[0].Value = ListID[i];
  77. newRow.Cells[1].Value = ListFirstname[i];
  78. newRow.Cells[2].Value = ListLastname[i];
  79. newRow.Cells[3].Value = ListTelephone[i];
  80. newRow.Cells[4].Value = ListAddress[i];
  81. dataGridView1.Rows.Add(newRow);
  82. }
  83. }
  84. }
  85. }
After you write down the program listings, press the F5 key to run the program and if you successfull connect your database the result is,

Load Datagridview From Database In C#
We have explained how to make a program in C# datagridview load data from a database. For those of you who want to download the source code of the program, you also can. Hopefully this discussion was helpful to you.
You can see Load Datagridview From Database C# from the Github project Here.
Thank you for reading this article! I hope it was useful to you. Visit My Github about .Net Csharp Here.