简体   繁体   中英

C# - Datagridview does not show data from MySQL

I have a datagridview which should contain all users in mysql database. For my problem, it adds rows based on the number of rows in the MySQL, but does not show any data on it. see image below (i have 2 rows in database):

screenshot

Here's my code that I've tried:

using MySql.Data.MySqlClient;

namespace SampleDatabaseQueries
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        MySqlConnection conn;
        MySqlCommand cmd;
        private void Main_Load(object sender, EventArgs e)
        {
            string connString = "server=localhost;user=root;password=;database=test_db";
            conn = new MySqlConnection(connString);

            showData();
        }

        public void showData()
        {

            string query = "SELECT * FROM test_db.users;";
            cmd = new MySqlCommand(query, conn);

            conn.Open();
            MySqlDataAdapter adapter = new MySqlDataAdapter();
            adapter.SelectCommand = cmd;
            DataTable dTable = new DataTable();
            adapter.Fill(dTable);

            dgUsers.DataSource = dTable;

            conn.Close();
        }
    }
}

EDIT: above code works, data was already loaded but it adds another column so I did not see at first (as you can see the long horizontal scroll on the above screenshot). To solve that, I removed the columns I manually added and changed my query to:

SELECT username AS Username, password AS Password FROM test_db.users;

Thank you!

Replace this:

MySqlDataAdapter adapter = new MySqlDataAdapter();

With:

using (MySqlDataAdapter reader = new MySqlDataAdapter(cmd))
{
    adapter.Fill(dTable);
}

EDIT

For further improvement you could make a database connection class, i suppose you are using the MySql connector from oracle so you can check out their documentation on how to do this. Here is a link that can get you started on the most basic things like connecting and filling datatables: MySql connector documentation

EDIT 1

As you said my solution did not work, here is another one that I just tested and should work.

DataTable dTable = new DataTable();
conn.Open();
string query = "SELECT * FROM test_db.users;";
MysqlCommand cmd = new MySqlCommand(query, conn);
using (MySqlDataAdapter reader = new MySqlDataAdapter(cmd))
{
    adapter.Fill(dTable);
}
dgUsers.DataSource = dTable;
conn.Close();

This should work. If the datatable is not showing any rows(Empty rows means it found something), then there is a different problem, maybe your database is empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM