我已经看到这个问题被问了很多,但我找到的答案对于我的VWD版本来说似乎已经过时了,因为它称之为“过时的”。我刚在学校学习,对此我非常陌生。我正在尝试为选中的网格视图中的每一行更新一个值。第一个检查值总是会更新,但第二个、第三个等值永远不会起作用,因为connectionstring属性尚未初始化。以下是我使用过的名称空间:
using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;这是让我遇到问题的代码(它位于一个按钮单击方法的内部)。第二次运行'try‘语句并试图打开连接时,似乎出现了错误:
string NewASNConnStr = ConfigurationManager.ConnectionStrings["Order"].ConnectionString;
SqlConnection ShipConnection = new
SqlConnection(ConfigurationManager.ConnectionStrings["Order"].ToString());
string insertSQL = "INSERT INTO [TRUCKS] ([DateSent]) VALUES (@DateSent)";
SqlCommand InsertCommand = new SqlCommand(insertSQL, ShipConnection);
InsertCommand.Parameters.Add("@DateSent", SqlDbType.Date).Value = DateTime.Now;
Int32 ASNNumber = GetASN();
foreach (GridViewRow grvRows in grvShipPallets.Rows)
{
if (((CheckBox)grvRows.FindControl("chkShip")).Checked)
{
string RFID = Convert.ToString(grvRows.Cells[1].Text);
SqlCommand UpdateCommand = new SqlCommand("UPDATE PALLETS SET TRUCKS$ASNNumber=@ASNNumber WHERE RFID=@RFID", ShipConnection);
UpdateCommand.Parameters.Add("@ASNNumber", System.Data.SqlDbType.Int).Value = ASNNumber;
UpdateCommand.Parameters.Add("@RFID", System.Data.SqlDbType.VarChar).Value= RFID;
ShipConnection.Open();
InsertCommand.ExecuteNonQuery();
ShipConnection.Close();
int InsertChecker = -2;
try
{
ShipConnection.Open();
InsertChecker = UpdateCommand.ExecuteNonQuery();
lblASNConfirmation.Text = "You have shipped the selected Order(s) on ASN # " + ASNNumber;
}
catch (Exception MyError)
{
lblError.Visible = true;
lblError.Text = "There has been an error with the database. <br/>";
lblError.Text += MyError.Message.ToString();
}
finally
{
ShipConnection.Dispose();
ShipConnection.Close();
}
}
}
grvShipPallets.DataBind();
}发布于 2011-05-12 10:10:26
试一试
string NewASNConnStr = ConfigurationManager.ConnectionStrings["Order"].ConnectionString;和
SqlConnection ShipConnection =
new SqlConnection(ConfigurationManager.ConnectionStrings["Order"].ConnectionString);而不是
string NewASNConnStr = ConfigurationManager.ConnectionStrings["Order"].ToString(); 和
SqlConnection ShipConnection =
new SqlConnection(ConfigurationManager.ConnectionStrings["Order"].ToString());发布于 2011-05-12 11:29:59
这是因为你在你的finally语句中处理了这个对象。因此,在随后的循环中,您的连接将不再作为对象存在。删除dispose行。关闭连接就足够了。在你不再需要它之前,不要丢弃它。
https://stackoverflow.com/questions/5972517
复制相似问题