将多个dataGridView绑定到MySQL数据库

时间:2011-05-22 08:44:49

标签: c# mysql datagridview datatable bindingsource

我有四个表的MySQL数据库,我编写了一个示例绑定方法。但是这个解决方案只适用于一个表。如果我绑定多个,dataGridViews将填充信息,但更新和删除命令运行不正常。

 public void Bind(DataGridView dataGridView, string tableName)
    {
        string query = "SELECT * FROM " + tableName;

        mySqlDataAdapter = new MySqlDataAdapter(query, conn);
        mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter);

        mySqlDataAdapter.UpdateCommand = mySqlCommandBuilder.GetUpdateCommand();
        mySqlDataAdapter.DeleteCommand = mySqlCommandBuilder.GetDeleteCommand();
        mySqlDataAdapter.InsertCommand = mySqlCommandBuilder.GetInsertCommand();

        dataTable = new DataTable();
        mySqlDataAdapter.Fill(dataTable);

        bindingSource = new BindingSource();
        bindingSource.DataSource = dataTable;

        dataGridView.DataSource = bindingSource;
    }

我应该为每个新表使用不同的mySqlDataAdapter或mySqlCommandBuilder吗?我使用了不同的DataTable和BindingSource对象,但是当我在一个表中插入新行时,我有一个异常,我在其他表中留下了空字段。有关此问题的任何解决方案或提示吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

Better late than never I guess...

I have an application that loads different tables into the same DataGridView using Visual Studio 2013. So far it is working!

1. DataTable

You certainly need to create a new one for each different table you want to load, otherwise you can not clear out the old data. You might think that

dataTable.Clear()

would do the trick but no, it leaves the old column headers behind so your new table is loaded to the right of all the old columns :-(. Although interestingly if your new table has a column with the same name as the old it merges them!

2. MySqlAdapter

I currently create a new one for each table, but at the very least your sql query is changing so you need to create a new SelectCommand:

MySqlCommand cmd = new MySqlCommand("SELECT * FROM `" + tableName + "`", conn);
sqlAdapter.SelectCommand = cmd;

I've tried this and it seems to work, but actually it is simpler to just create a new MySqlAdapter and performance really isn't an issue at this point!

3. SqlCommandBuilder

Yes you should create a new one because the update and delete commands will be different. I don't use a class variable but create one dynamically (i.e. as a local variable) when I need it.

4. BindingSource

I don't believe you need a new BindingSource, but I haven't used them very much so can't be certain.