[英]How can I display data in data grid view
我有一个组合框,可以在其中显示数据库中所有表的名称。 现在,我找不到一种方法,可以通过在组合框中选择表名来在数据网格视图中显示表的所有内容。 目前我有 2 个表,我可以通过在组合框中选择它并在数据网格视图中显示它的值来进行选择。
我想要实现的是,通过在组合框中选择表名,我的数据网格视图将根据组合框中选择的表名显示表的值
这是我的代码:
private void samples_Load(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection(conn);
try
{
con.Open();
MySqlCommand sqlCmd = new MySqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select table_name from information_schema.tables where table_schema = 'attenddb'";
MySqlDataAdapter sqlDataAdap = new MySqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "TABLE_NAME";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string query2 = "select table_name from ['"+ comboBox1.Text + "']";
MySqlConnection con2 = new MySqlConnection(conn);
MySqlCommand com2 = new MySqlCommand(query2, con2);
MySqlDataAdapter myadapt = new MySqlDataAdapter();
myadapt.SelectCommand = com2;
DataTable dtable = new DataTable();
myadapt.Fill(dtable);
dataGridView1.DataSource = dtable;
}
catch
{
MessageBox.Show("Error Loading data");
}
}
以下是您的代码的一些问题:
如果要在数据网格视图中显示数据,可以参考以下代码:
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("table_name1");
comboBox1.Items.Add("table_name2");
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string query2 = "select * from " + comboBox1.Text;
MySqlConnection con2 = new MySqlConnection(conn);
con2.Open();
try
{
MySqlCommand com2 = new MySqlCommand(query2, con2);
MySqlDataAdapter myadapt = new MySqlDataAdapter();
myadapt.SelectCommand = com2;
DataTable dtable = new DataTable();
myadapt.Fill(dtable);
dataGridView1.DataSource = dtable;
}
catch
{
MessageBox.Show("Error Loading data");
}
finally
{
if (con2.State == ConnectionState.Open)
{
con2.Close();
}
}
}
您必须 select 所选表中所有带*
的列。
string query2 = "select * from ["+ comboBox1.Text + "]";
或使用字符串插值:
string query2 = $"select * from [{comboBox1.Text}]";
并且不要在表名周围使用单引号(您已经有了方括号),因为您直接想要名称而不是字符串文字。
不要使用括号 [] 和单引号。
string query2 = "select columnname from " + comboBox1.Text+ "";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.