这里我需要访问for循环之外的变量delval
,如下面的代码所示
cmd_mail.Parameters.Add("@deleteusers", SqlDbType.NVarChar).Value = delval;
..怎么做..
这是我的代码
for (int i = 0; i <= NoOfUsers - 1; i++) {
using (SqlConnection Conn = new SqlConnection(constr_str)) {
using (SqlCommand cmd = new SqlCommand()) {
cmd.Connection = Conn;
Conn.Open();
cmd.CommandText = "Select top 1 Login_User_Name from Rode_Provisioning_User where RequestId=@RequestId and CustomerCode =@CustomerCode and disableflag=0 order by User_Count";
cmd.Parameters.Add("@CustomerCode", SqlDbType.VarChar).Value = CustomerCode;
cmd.Parameters.Add("@RequestId", SqlDbType.VarChar).Value = RequestId;
string Loginusername = cmd.ExecuteScalar();
Conn.Close();
string delval = "";
if (string.IsNullOrEmpty(delval)) {
delval = Loginusername;
} else {
delval = delval + "," + Loginusername;
}
}
}
}
if (flag == "Yes") {
string constr_dep = "server=" + _strServer + ";database=" + _strDatabase + ";uid=" + _strUserid + ";pwd=" + _strPassword + ";";
SqlConnection con_dep = new SqlConnection();
con_dep.ConnectionString = constr_dep;
SqlCommand cmd_mail = new SqlCommand("delete_user_mailsend_sp", con_dep);
cmd_mail.CommandType = CommandType.StoredProcedure;
cmd_mail.CommandTimeout = 0;
cmd_mail.Parameters.Add("@companycode", SqlDbType.NVarChar).Value = CustomerCode
cmd_mail.Parameters.Add("@deleteusers", SqlDbType.NVarChar).Value = delval;
try {
con_dep.Open();
cmd_mail.ExecuteNonQuery();
} catch (SqlException ee) {
VWLogger.LogMessage("Exception in delete_user_mailsend_sp:", TraceEventType.Critical);
VWLogger.LogMessage(ee, TraceEventType.Critical);
return ee.Message;
flag = ee.Errors(0).ToString();
}
con_dep.Close();
}
有什么建议吗?
答案 0 :(得分:5)
然后在循环外定义它,它将在两个块以及外部可见。
答案 1 :(得分:0)
正如zerkms所说,在循环之外声明它。见下文。
string delval = "";
for (int i = 0; i <= NoOfUsers - 1; i++)
{
// your existing stuff
// ...
if (string.IsNullOrEmpty(delval))
{
delval = Loginusername;
}
else
{
delval = delval + "," + Loginusername;
}
}
if (flag == "Yes")
{
// your existing stuff
// ...
cmd_mail.Parameters.Add("@deleteusers", SqlDbType.NVarChar).Value = delval;
}