读书人

一段十分简单的代码,走过的路过的千万

发布时间: 2011-12-12 22:59:56 作者: rapoo

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

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就过了生命周期了
------解决方案--------------------


search 要声明在外面
sda.Fill(ds, "表名 ");
[解决办法]
把string search=""
定义在con.Open();前面.
如果在if...else块里面定义变量,只在块内有意义.


[解决办法]
用全局变量,不能用局部变量

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

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

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( "出错了 ");
}

另外this.TextBox1.Text这样就行,不用再ToString() ,还有就是没看出if和else里有什么区别,为什么这么写

读书人网 >asp.net

热点推荐