• We just launched and are currently in beta. Join us as we build and grow the community.

Filling Data in a ListBox Using C# and MySQL Database

0mni

UX/UI Master
0 Rep
0
0
0
Rep
0
0 Vouches
0
0
0
Vouches
0
Posts
43
Likes
55
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 200 XP
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#.
creating_application_c_3.png

Step 2

Do the form just like shown below.
from1listbox.png

Step 3

Press F7 to open the code editor. In the code editor, add a namespace to access MySQL

libraries

  1. 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. MySqlConnection con =

    new

    MySqlConnection(

    "server=localhost;user id=root;password=;database=dbpeople;sslMode=none"

    )

    ;
  2. MySqlCommand cmd;
  3. MySqlDataAdapter da;
  4. DataTable dt;
  5. string

    sql;

Step 5

Create a method to fill the data inside a ListBox.

  1. private

    void

    fill_data(

    string

    sql,ListBox lst)
  2. {
  3. try
  4. {
  5. con.

    Open

    (

    )

    ;
  6. cmd =

    new

    MySqlCommand(

    )

    ;
  7. da =

    new

    MySqlDataAdapter(

    )

    ;
  8. dt =

    new

    DataTable(

    )

    ;

  9. cmd.

    Connection

    =

    con;
  10. cmd.

    CommandText

    =

    sql;
  11. da.

    SelectCommand

    =

    cmd;
  12. da.

    Fill

    (

    dt)

    ;

  13. lst.

    DataSource

    =

    dt;
  14. lst.

    DisplayMember

    =

    "FNAME"

    ;

  15. }
  16. catch

    (

    Exception ex)
  17. {
  18. MessageBox.

    Show

    (

    ex.

    Message

    )

    ;

  19. }
  20. finally
  21. {
  22. con.

    Close

    (

    )

    ;
  23. da.

    Dispose

    (

    )

    ;
  24. }

  25. }

Step 6

Writ the following codes to execute the method in the first load of the form.

  1. private

    void

    Form1_Load(

    object

    sender, EventArgs e)
  2. {
  3. sql =

    "SELECT FNAME FROM `tblperson`"

    ;
  4. fill_data(

    sql, listBox1)

    ;
  5. }

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.


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

452,496

327,345

327,353

Top