How can I display data in the data grid view by selecting my database table in my combo box? I am struggling to display the specific data from the table selected in the combo box. This is on c# and MySQL.
here is my code:
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");
}
}
CodePudding user response:
Don't use Bracket [] and single quotes.
string query2 = "select columnname from " comboBox1.Text "";
CodePudding user response:
You must select all the columns with *
from the selected table.
string query2 = "select * from [" comboBox1.Text "]";
or with string interpolation:
string query2 = $"select * from [{comboBox1.Text}]";
And also, do not use single quotes around the table name (you already have the square brackets), since you want the name directly and not as string literal.