2015-11-08 87 views
-1

我在頁面C#ASP.NET傳遞,如果else語句字符串值到另一個字符串

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(); 
     } 
} 

有這樣的代碼我如何我myquery字符串值設置爲我的if else語句在我的頁面加載類?我現在的代碼總是設置爲myquerynull

+4

您在if條件申報 「更改爲MyQuery」 再次讀取數據,去除串關鍵字如果CAND else條件,然後再試一次。 –

回答

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(); 
    } 
} 
0

在您的if/else語句中,您將再次聲明myquery。如果你刪除了字符串關鍵字,你應該是金色的;

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語句的新變量,導致失去對他們鬧翻範圍創建後步驟,所以你也不能訪問它們。

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(); 
相關問題