我一直是“如果它没有坏就不要修复它”的粉丝,但我的代码虽然可以正常运行,但会抛出connectionstring 属性尚未初始化消息。类似的帖子表明连接字符串为空---所以我if IsNullOrEmpty
在连接打开命令周围添加了一个。这是引发异常的行。注意:我的连接字符串是从连接字符串数据库中检索的。这是 .aspx 页面的 c# 代码隐藏文件。预先感谢您对异常原因的任何建议。
编码:
using (SqlConnection sconn = new SqlConnection(someconnectionstring.Value.ToString()))
{
using (SqlCommand scmd = new SqlCommand("mydb.[dbo].[myStoredProc]", sconn))
{
scmd.CommandType = CommandType.StoredProcedure;
scmd.Parameters.Add("@valueX", SqlDbType.VarChar).Value = 2;
scmd.Parameters.Add("@returnValue", SqlDbType.Int);
scmd.Parameters["@returnValue"].Direction = ParameterDirection.Output;
//testing for null as suggested...
if (!string.IsNullOrEmpty(sconn.ToString()) || sconn.ToString() != "") //the || != "" may be double work.. not sure
{
sconn.Open(); //code throw exception here but continues to work.
SqlDataReader adar = scmd.ExecuteReader();
if (adar.HasRows)
{
while (adar.Read())
{
hiddenfieldX.Value = adar["valueX"].ToString();
...
}
sconn.Close();
}
}
}
}
}
catch (SqlException er)
{
//The ConnectionString property has not been initialized thrown here
}