开发者

DataAdapter.Fill NullReferenceException after DataTable.Columns.Clear and column sort

I'm using MySQL with C# and a DataGridView.

The problem happens when the users clicks on a column to sort it, followed by an action which forces the columns to be cleared (Happens when an user ticks off which columns to see in using checkboxes).

The actual exception is thrown at dataAdapter.Fill(dt).

The code works fine when the user does not sort the actual columns. It also works fine after the user has rearranged columns.

This is my code:

    public void GetDataAndFilter(string selectQuery, bool colChange)
    {
        using (var conn = connect())
        {
            MySqlCommand cmd = 开发者_如何学编程new MySqlCommand(selectQuery, conn);
            dataAdapter = new MySqlDataAdapter(cmd);
            dt.Clear();

            if (colChange)
                dt.Columns.Clear();

            dataAdapter.Fill(dt);

            conn.Close();
        }
    }

I've been trying to fix this for some time but I've run out of ideas.

Thanks for your time, I appreciate it.


I think it's better to clear following line :

dt.Clear();

dt.Columns.Clear();

and instantiate your dt again instead of clear its column and itself.

dt = new DataTable();

hope this help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜