我的页面中有此代码
public partial class Reports : System.Web.UI.Page
{
private string myquery = null;
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
usertype = Session["usertype"].ToString();
{
if (usertype == "admin")
{
string myquery = @"SELECT jobId, odometerReading, jobDescription, status FROM joborder Where truck_id = '" + truck_id + "'";
}
else
{
string myquery = @"SELECT jobId, odometerReading, jobDescription, status FROM joborder Where truck_id = '" + truck_id + "' and status = '1'";
}
}
connectDB();
}
}
如何在我的pageload类中将myquery
字符串值设置为if else语句?我当前的代码始终将myquery
设置为null
。
答案 0 :(得分:0)
在你的if / else语句中,你是第二次声明myquery。如果你删除了string关键字,你应该是金色的;
if (usertype == "admin")
{
myquery = @"SELECT jobId, odometerReading, jobDescription, status FROM joborder Where truck_id = '" + truck_id + "'";
}
else
{
myquery = @"SELECT jobId, odometerReading, jobDescription, status FROM joborder Where truck_id = '" + truck_id + "' and status = '1'";
}
目前,您在if / else语句中创建的新变量由于它们在创建后超出范围而丢失,因此您也无法访问它们。
答案 1 :(得分:0)
public partial class Reports : System.Web.UI.Page
{
private string myquery = string.Emplty; //Try use this
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
usertype = Session["usertype"].ToString();
if (usertype == "admin")
{
myquery = @"SELECT jobId, odometerReading, jobDescription, status FROM joborder Where truck_id = '" + truck_id + "'";
}
else
{
myquery = @"SELECT jobId, odometerReading, jobDescription, status FROM joborder Where truck_id = '" + truck_id + "' and status = '1'";
}
connectDB();
}
}
答案 2 :(得分:0)
使用sql数据读取器从sql server读取数据
SqlCommand command ;
if (usertype == "admin")
{
command = new SqlCommand("SELECT jobId, odometerReading, jobDescription, status FROM joborder Where truck_id = '" + truck_id + "'",connection);
connection.Open();
}
else
{
command = new SqlCommand("SELECT jobId, odometerReading, jobDescription, status FROM joborder Where truck_id = '" + truck_id + "' and status = '1'",connection);
connection.Open();
}
SqlDataReader reader = command.ExecuteReader();