在c#中使用语句不会关闭连接。为什么?
我正在创建一个crud gridview网页,我在代码中使用ASP.NET中的“using”语句,因为我了解到它会自动转换其中的代码,所以我不必使用在c#中使用语句不会关闭连接。为什么?,c#,asp.net,sql-server,using,C#,Asp.net,Sql Server,Using,我正在创建一个crud gridview网页,我在代码中使用ASP.NET中的“using”语句,因为我了解到它会自动转换其中的代码,所以我不必使用connect.Close() 但我还是犯了一个错误: System.InvalidOperationException:连接未关闭。连接的当前状态为“打开” 我试图将connection.Close()放入但仍然会发生相同的错误 这是我的密码。谁能帮我解决这个问题吗?多谢各位 void PopulateGridView() { using
connect.Close()代码>
但我还是犯了一个错误:
System.InvalidOperationException:连接未关闭。连接的当前状态为“打开”
我试图将connection.Close()放入代码>但仍然会发生相同的错误
这是我的密码。谁能帮我解决这个问题吗?多谢各位
void PopulateGridView()
{
using (connect)
{
connect.Open();
adapter = new SqlDataAdapter("SELECT * FROM RetailInfo", connect);
table = new DataTable();
adapter.Fill(table);
}
if(table.Rows.Count > 0)
{
RetailInfoGridView.DataSource = table;
RetailInfoGridView.DataBind();
}
else
{
table.Rows.Add(table.NewRow());
RetailInfoGridView.DataSource = table;
RetailInfoGridView.DataBind();
RetailInfoGridView.Rows[0].Cells.Clear();
RetailInfoGridView.Rows[0].Cells.Add(new TableCell());
RetailInfoGridView.Rows[0].Cells[0].ColumnSpan = table.Columns.Count;
RetailInfoGridView.Rows[0].Cells[0].Text = "No record Found";
}
}
在connect.Open()之前有一个简单的修复程序,您可以执行以下操作:
if (connect.State == ConnectionState.Open)
{
connect.Close();
}
此外,正如Zohar Peled指出的那样,使用(var connect=new SqlConnection(connectionString))而不是在类级别声明对象是很好的
这样就不会发生泄漏,连接件在工作完成后即被处理。更换此零件
using (connect)
{
connect.Open();
adapter = new SqlDataAdapter("SELECT * FROM RetailInfo", connect);
table = new DataTable();
adapter.Fill(table);
}
到
该连接变量在应用程序的其他地方再次使用。这是否回答了您的问题?错误发生在哪一行?是connect
类型的System.Data.SqlClient.SqlConnection
?使用(connect)
应该是使用(var connect=new SqlConnection(connectionString))
顺便说一句,适配器。如果连接关闭,Fill
将打开连接,因此您不需要connect.open()
line。非常感谢您的帮助。我解决了。他是对的。我使用变量连接3次。非常感谢你!
using (connect)
{
if (connect.State == ConnectionState.Open)
connect.Close();
connect.Open();
adapter = new SqlDataAdapter("SELECT * FROM RetailInfo", connect);
table = new DataTable();
adapter.Fill(table);
connect.Close();
}