在当前上下文中不存在“变量"

编程入门 行业动态 更新时间:2024-10-26 04:19:49
本文介绍了在当前上下文中不存在“变量"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我收到一条错误消息,指出"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.

更多推荐

在当前上下文中不存在“变量"

本文发布于:2023-11-09 15:10:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572692.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上下文   中不   变量   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!