日期:2014-05-18  浏览次数:20406 次

一段非常简单的代码,走过的路过的千万不要错过!!

                con.Open();
                if   (this.下拉列表.SelectedValue   ==   "什么什么 ")
                {
                        string   search   =   "Select   *   from   表   where   字段   Like   '% "   +   this.TextBox1.Text.ToString()   +   "% ' ";
 
                }
                else
                {
                        string   search   =   "Select   *   from   表   where   字段   Like   '% "   +   this.TextBox1.Text.ToString()   +   "% ' ";
                }
             
                try
                {
                                SqlDataAdapter   sda   =   new   SqlDataAdapter(search,   con);
                                DataSet   ds   =   new   DataSet();
                                sda.Fill(ds,   "MapDevice ");
                                this.DeviceViewGv.DataSource   =   ds.Tables[ "MapDevice "];
                                this.DeviceViewGv.DataBind();
                  }
                        catch
                  {
                                Response.Write( "出错了 ");
                  }


问题是:编译错误  
说明:   在编译向该请求提供服务所需资源的过程中出现错误。请检查下列特定错误详细信息并适当地修改源代码。  

编译器错误信息:   CS0103:   当前上下文中不存在名称“search”


怎样才能正确呢?

------解决方案--------------------
string search = " ";
if (this.下拉列表.SelectedValue == "什么什么 ")
{
search = "Select * from 表 where 字段 Like '% " + this.TextBox1.Text.ToString() + "% ' ";

}
else
{
search = "Select * from 表 where 字段 Like '% " + this.TextBox1.Text.ToString() + "% ' ";
}

------解决方案--------------------
你将那个search变量定义到最外面就可以.
------解决方案--------------------
search定义在if外部,你这样定义是局部变量,if执行完后search就过了生命周期了