Filling Data in a ListBox Using C# and MySQL Database

In this tutorial, I will teach you how to fill data in a ListBox using C# and MySQL database. This process will illustrate how to get the data in the database and display it on a ListBox. This operation will be a big help for you when you are dealing with a ListBox and MySQL Database.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application for c#. ps1

Step 2

Do the form just like shown below. ps2

Step 3

Press F7 to open the code editor. In the code editor, add a namespace to access MySQL libraries
  1.  
  2. using MySql.Data.MySqlClient;

Step 4

Create a connection between C# and MySQL database. After that, declare all the classes and variable that is needed.
  1.  
  2.  
  3.         MySqlConnection con = new MySqlConnection("server=localhost;user id=root;password=;database=dbpeople;sslMode=none");
  4.         MySqlCommand cmd;
  5.         MySqlDataAdapter da;
  6.         DataTable dt;
  7.         string sql;

Step 5

Create a method to fill the data inside a ListBox.
  1.  
  2.         private void fill_data(string sql,ListBox lst)
  3.         {
  4.             try
  5.             {
  6.                 con.Open();
  7.                 cmd = new MySqlCommand();
  8.                 da = new MySqlDataAdapter();
  9.                 dt = new DataTable();
  10.  
  11.                 cmd.Connection = con;
  12.                 cmd.CommandText = sql;
  13.                 da.SelectCommand = cmd;
  14.                 da.Fill(dt);
  15.  
  16.                 lst.DataSource = dt;
  17.                 lst.DisplayMember = "FNAME";
  18.  
  19.             }
  20.             catch (Exception ex)
  21.             {
  22.                 MessageBox.Show(ex.Message);
  23.  
  24.             }
  25.             finally
  26.             {
  27.                 con.Close();
  28.                 da.Dispose();
  29.             }
  30.  
  31.         }

Step 6

Writ the following codes to execute the method in the first load of the form.
  1.  
  2.         private void Form1_Load(object sender, EventArgs e)
  3.         {
  4.             sql = "SELECT FNAME FROM `tblperson`";
  5.             fill_data(sql, listBox1);
  6.         }
The complete source code is included you can download it and run it on your computer. For any questions about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT Or feel free to comment below.

Add new comment