C# 用 MySQL 数据填充 Datagridview
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12904854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fill Datagridview with MySQL data
提问by Catalin Mihai
i tried several times to make it work but it just doesn't fill up the datagridview with mysql data ,here's my code :
我尝试了几次使其工作,但它只是没有用 mysql 数据填充 datagridview,这是我的代码:
string connectionString = "SERVER=localhost;DATABASE=shootsource;UID=root;PASSWORD=;";
string sql = "SELECT * FROM characters";
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
sCommand = new MySqlCommand(sql, connection);
sAdapter = new MySqlDataAdapter(sCommand);
sBuilder = new MySqlCommandBuilder(sAdapter);
sDs = new DataSet();
sAdapter.Fill(sDs, "characters");
sTable = sDs.Tables["characters"];
connection.Close();
dataGridView1.DataSource = sDs.Tables["characters"];
dataGridView1.ReadOnly = true;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
It shows only the columns from the mysql table 'characters' : id,name,time etc...how can i populate it from the db?
它只显示 mysql 表 'characters' 中的列:id、name、time 等......我如何从数据库中填充它?
Here is an image of the problem:
这是问题的图像:


回答by AntLaC
After you set your DataSource you need to do a DataBind
设置 DataSource 后,您需要执行 DataBind
dataGridView1.DataBind();
回答by Taco2
private void MySQL_ToDatagridview()
{
//VarribleKeeper.MySQLConnectionString = your connection string
//info being your table name
MySqlConnection mysqlCon = new
MySqlConnection(VarribleKeeper.MySQLConnectionString);
mysqlCon.Open();
MySqlDataAdapter MyDA = new MySqlDataAdapter();
string sqlSelectAll = "SELECT * from info";
MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, mysqlCon);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
}

