请看我的代码string Id;
protected void Page_Load(object sender, EventArgs e)
{ Id = Request.QueryString["cateId"]; }
public string List()
{
if (Id == "0")
{
string strSql = "SQL语句A";
}
else {
string strSql = "SQL语句B";
}
//省略
SqlCommand cmd = new SqlCommand(strSql, objConnection);
//省略
}
我代码写成这样,提示错误说,不存在 strSql,请问这个错在什么地方呢?
protected void Page_Load(object sender, EventArgs e)
{ Id = Request.QueryString["cateId"]; }
public string List()
{
if (Id == "0")
{
string strSql = "SQL语句A";
}
else {
string strSql = "SQL语句B";
}
//省略
SqlCommand cmd = new SqlCommand(strSql, objConnection);
//省略
}
我代码写成这样,提示错误说,不存在 strSql,请问这个错在什么地方呢?
public string List()
{
string strSql ;
if (Id == "0")
{
strSql = "SQL语句A";
}
else {
strSql = "SQL语句B";
}
//省略
SqlCommand cmd = new SqlCommand(strSql, objConnection);
//省略
}
string strSql="";写在最上面试试吧..下面就写if (Id == "0")
{
strSql = "SQL语句A";
}
else {
strSql = "SQL语句B";
}
{
string strSql ="";
if (Id == "0")
{
strSql = "SQL语句A";
}
else {
strSql = "SQL语句B";
}
//省略
SqlCommand cmd = new SqlCommand(strSql, objConnection);
//省略
}
string Id; protected void Page_Load(object sender, EventArgs e)
{
Id = Request.QueryString["cateId"];
} public string List()
{ string strSql; //<----
if (Id == "0")
{
strSql = "SQL语句A";
}
else
{
strSql = "SQL语句B";
}
//...
SqlCommand cmd = new SqlCommand(strSql, objConnection);
}
{
string strSql = "SQL语句B";
if (Id == "0")
{
strSql = "SQL语句A";
}
//省略
SqlCommand cmd = new SqlCommand(strSql, objConnection);
//省略
}
public string List()
{
if (Id == "0")
{
string strSql = "SQL语句A";
}
else {
string strSql = "SQL语句B";
}
写成这样
string strSql;
public string List()
{
if (Id == "0")
{
strSql = "SQL语句A";
}
else {
strSql = "SQL语句B";
}
{
if (Id == "0")
{
string strSql = "SQL语句A";
}
else {
string strSql = "SQL语句B";
}
//省略
SqlCommand cmd = new SqlCommand(strSql, objConnection);
//省略
}
因为你定义的strSql 时局部变量
他的作用范围在if里面所有在这句话的时候他不知道strSql在那里定义的
SqlCommand cmd = new SqlCommand(strSql, objConnection);
protected void Page_Load(object sender, EventArgs e)
{ Id = Request.QueryString["cateId"]; }
public string List()
{
string strSql = null;
if (Id == "0")
{
strSql = "SQL语句A";
}
else {
strSql = "SQL语句B";
}
//省略
SqlCommand cmd = new SqlCommand(strSql, objConnection);
//省略
}
我代码写成这样,提示错误说,不存在 strSql,请问这个错在什么地方呢?
你先在string Id; 上添加一个string strSql ="";
然后在IF和ELSE里把string strSql 的string去掉就行了。