在当前上下文中不存在“变量" [英] 'variable' does not exist in the current context

查看:94
本文介绍了在当前上下文中不存在“变量"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一条错误消息,指出"sql"在当前上下文中不存在.有人可以告诉我解决方法吗?这是示例代码...

I am getting an error that says "The name ''sql'' does not exist in the current context. Can someone tell me a work around for this? here is the sample code...

if (btnUpdate.Text == "New")
           {
               string sql = "insert into MorningBriefings (department, date, equipment, staffing, specialprocedures, notes, clinics) values (@department, @date, @equipment, @staffing, @specialprocedures, @notes, @clinics)";
           }
           else
           {
               string sql = "update MorningBriefings set equipment=@equipment, staffing=@staffing, specialprocedures=@specialprocedures, notes=@notes, clinics=@clinics where department=@department and date=@date";
           }

           try
           {
               conn.Open();
               SqlCommand cmd = new SqlCommand(sql, conn);
            ....
           }

推荐答案

您做错了.为什么不在if-else条件之外声明sql?这样.

Your''e doing it wrong. Why not do the declaration of sql outside your if-else condition? like this.

string sql;
if(btnUpdate.Text == "New")
{
   sql = "insert into MorningBriefings (department, date, equipment, staffing, specialprocedures, notes, clinics) values (@department, @date, @equipment, @staffing, @specialprocedures, @notes, @clinics)";
}
else
{
   sql = "update MorningBriefings set equipment=@equipment, staffing=@staffing, specialprocedures=@specialprocedures, notes=@notes, clinics=@clinics where department=@department and date=@date";
}

 try
 {
    conn.Open();
    SqlCommand cmd = new SqlCommand(sql, conn);
    ....
 }


您已经声明了两个称为sql的不同变量,它们均是各自代码块中的局部变量.由于无法在变量范围之外访问变量,因此这就是为什么当您尝试在try ... catch块中使用sql时收到错误消息的原因.它在那里不存在,并且不在其他两个实例的范围之内.

如另一篇文章中所述,我仅声明1个sql变量,并将其置于整个结构的范围内.那将涉及到将声明放置在块之前.
You have declared 2 different variables called sql, both as local variables in the respective code blocks. Since the variables aren''t accessible outside their scope, that''s why you get the error message when you try to use sql in the try ... catch block. It doesn''t exist there and is out of scope of both of the other instances.

As mentioned in the other post, I''d declare only 1 sql variable and make it in the scope of the entire structure. That would involve placing the declaration before the if ... then ... else block.


这篇关于在当前上下文中不存在“变量"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆