【发布时间】:2019-12-20 15:02:27
【问题描述】:
我正在创建一个 crud gridview 网页,并在我的代码中使用 ASP.NET 中的“使用”语句,因为我了解到它会自动转换其中的代码,因此我不必使用 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是System.Data.SqlClient.SqlConnection类型的吗? -
using (connect)应该是using (var connect = new SqlConnection(connectionString))顺便说一句,adapter.Fill将在连接关闭时打开连接,因此您不需要connect.Open()行。 -
非常感谢您的帮助。我解决了。他是对的。我使用了可变连接 3 次。非常感谢!
标签: c# asp.net sql-server using