C# 尝试将datatable加载到datagridview会导致崩溃

C# 尝试将datatable加载到datagridview会导致崩溃,c#,visual-studio-2012,datagridview,datatable,C#,Visual Studio 2012,Datagridview,Datatable,我有一个简单的DB应用程序,允许用户搜索MSSQL表中的某些特定术语,然后将找到的结果导出到日志文件中 我遇到了一个奇怪的bug,它会导致应用程序冻结,但只有在我运行“Release”版本时,而不是在VisualStudio内部运行调试版本时。我可以毫无问题地运行各种查询。但是,如果我运行的第一个查询返回0个结果,那么在尝试将结果从datatable加载到datagrid视图时,返回任何结果的下一个查询将始终失败 我很确定它会崩溃,因为我没有遵循我这边的最佳实践,但我不完全确定为什么 下面是被截

我有一个简单的DB应用程序,允许用户搜索MSSQL表中的某些特定术语,然后将找到的结果导出到日志文件中

我遇到了一个奇怪的bug,它会导致应用程序冻结,但只有在我运行“Release”版本时,而不是在VisualStudio内部运行调试版本时。我可以毫无问题地运行各种查询。但是,如果我运行的第一个查询返回0个结果,那么在尝试将结果从datatable加载到datagrid视图时,返回任何结果的下一个查询将始终失败

我很确定它会崩溃,因为我没有遵循我这边的最佳实践,但我不完全确定为什么

下面是被截断的代码片段

//Declared in the start of the class
DataTable DBResults = new DataTable();


//This is run inside of a method called by a background worker.
DBResults.Clear();

SqlDataAdapter da = new SqlDataAdapter(sqlQuery, SQLConnection);
SqlConnection SQLCon = new SqlConnection(getConnectionString());

//This is wrapped inside a try/catch/finally.
SQLCon.Open();
da.Fill(DBResults);
SQLCon.Close();

//Finally, push the data into the Datagridview inside of the form.
//This is the line that will always freeze the app when running a Final build, but not a debug build.
dataGridView_Results.DataSource = new DataView(DBResults);

this.dataGridView_Results.Refresh();


//I discovered that if I changed the crashing line to copy instead, it won't crash:
dataGridView_Results.DataSource = new DataView(DBResults.Copy());

我假设这是因为数据源仍然有一个指向DbResults的指针。但奇怪的是,只有在第一次搜索返回0个结果时,如果我有结果,它才不会引起问题。如果这有什么不同的话,那就是visual studio 2012.NET 4。

Etan,您应该直接将数据表分配给datagridview的datasource属性,而不必执行新的操作。应该是这样的:

dataGridView_Results.DataSource = DBResults;

我真的不太了解下面这行的copy属性。

您尝试过dataGridView_Results.DataSource=DBResults吗?我编辑过您的标题。请参阅“”,其中的共识是“不,他们不应该”。您提到了一位backgroundworker,这使得您可能是多线程的。请你也出示一下你打的电话好吗。您可能正在从另一个线程操作UI。