英文:
How to switch different table throgh the combobox without adding additional column
问题
I have a database named appmondb and I want to use the combobox to switch tables. If I select the ids table first, it is no problem, but if I select the accounts table next, the fields of ids and accounts will appear at the same time.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
currentdt.Clear();//clear table
dataGridView1.DataSource = null;
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand cmd;
string sql = "SELECT * FROM " + comboBox1.Text;
cmd = new MySqlCommand(sql, Connection.connMaster);
adapter.SelectCommand = cmd;
adapter.Fill(currentdt);
dataGridView1.DataSource = currentdt;
totalPage = calculateTotalPages(currentdt);//update totalPage
}
after that, I select accounts table
I have something to say that it should be .fill() or the wording of dataset and datatable
英文:
I have a database named appmondb and I want to use the combobox to switch tables. If I select the ids table first, it is no problem, but if I select the accounts table next, the fields of ids and accounts will appear at the same time.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
currentdt.Clear();//clear table
dataGridView1.DataSource = null;
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand cmd;
string sql = "SELECT * FROM " + comboBox1.Text;
cmd = new MySqlCommand(sql, Connection.connMaster);
adapter.SelectCommand = cmd;
adapter.Fill(currentdt);
dataGridView1.DataSource = currentdt;
totalPage = calculateTotalPages(currentdt);//update totalPage
}
after that, I select accounts table
I have something to say that it should be .fill() or the wording of dataset and datatable
答案1
得分: 1
Calling Clear on the DataTable removes all the rows but it doesn't remove the columns, so they are still there when you call Fill for the new query. You'll need to either create a new DataTable each time or else Clear the Columns collection as well.
I'm fairly certain that clearing the DataSource is not going to remove any columns from the grid either, so you're going to have to Clear the Columns collection of the grid too. Like so:
dataGridView1.DataSource = null;
dataGridView1.Columns.Clear();
currentdt.Clear();
currentdt.Columns.Clear();
英文:
Calling Clear on the DataTable removes all the rows but it doesn't remove the columns, so they are still there when you call Fill for the new query. You'll need to either create a new DataTable each time or else Clear the Columns collection as well.
I'm fairly certain that clearing the DataSource is not going to remove any columns from the grid either, so you're going to have to Clear the Columns collection of the grid too. Like so:
dataGridView1.DataSource = null;
dataGridView1.Columns.Clear();
currentdt.Clear();
currentdt.Columns.Clear();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论