phpmyadmin 如何在数据网格视图中显示数据

6ovsh4lw  于 2022-11-09  发布在  PHP
关注(0)|答案(3)|浏览(136)

我有一个组合框,可以在其中显示数据库中所有表的名称。现在,我找不到一种方法,可以通过在组合框中选择表名称来在数据网格视图中显示表的所有内容。目前,我有两个表,可以通过在组合框中选择表来进行选择,并在数据网格视图中显示表的值。
我试图实现的是,通过在组合框中选择表名,我的数据网格视图将根据在组合框中选择的表名来显示表的值
下面是我代码:

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");
    }
}
dkqlctbz

dkqlctbz1#

以下是您的代码中的一些问题:
1.我们可以使用“select * from“+组合框1.Text;以从数据库中获取数据。
1.在访问数据库之前,我们必须打开连接。
如果要在数据网格视图中显示数据,可以参考下面的代码:

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();
            }
        }
    }
oipij1gg

oipij1gg2#

不要使用方括号[]和单引号。

string query2 = "select columnname from " + comboBox1.Text+ "";
deikduxw

deikduxw3#

必须从所选表中选择所有包含*的列。

string query2 = "select * from ["+ comboBox1.Text + "]";

或使用字符串插值:

string query2 = $"select * from [{comboBox1.Text}]";

另外,不要在表名前后使用单引号(您已经使用了方括号),因为您希望直接使用名称,而不是字符串文字。

相关问题