Issue
I have a combo box where I show all the names of my tables inside my database. Now I can't find a way where I can display all the content of my table in data grid view by selecting a table name in my combo box. Currently I have 2 tables where I can choose by selecting it in combo box and display its values in data grid view.
What I'am trying to achieve is, by selecting the table names in combo box my data grid view will display the values of the table depending on what table name is selected in my combo box
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");
}
}
Solution
Here are some problems with your code:
- We could use "select * from " + comboBox1.Text; to get the data from the database.
- It is necessary for us to open the connection before we want to access the database.
If you want to display data in data grid view, you can refer to the following code:
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();
}
}
}
Answered By - Jingmiao Xu-MSFT
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.