我试了几次让它工作但它只是没有用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;
它只显示mysql表'characters'中的列:id,name,time等...如何从db填充它?
以下是问题的图片:
答案 0 :(得分:9)
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;
}
答案 1 :(得分:0)
设置DataSource后,需要执行DataBind
dataGridView1.DataBind();