2015-01-08 45 views
0

我正在創建一個用於在酒店預訂房間的模塊。選擇房間後,房間號碼將顯示在標籤中。單擊確定按鈕時,執行以下代碼。當我檢查房間的可用性時,即使它是「否」,標誌不會被初始化爲1.任何人都可以指導我在哪裏出錯。數據讀取器具有行,但其值的比較從不爲真

protected void ok_room(object sender, EventArgs e) 
{ 
    if (Label1.Text != "") 
    { 
     int result = 0; 
     int flag = 0; 

     string[] room = Label1.Text.Split(new char[] { ' ' }); 

     cmd = new SqlCommand(); 
     cmd1 = new SqlCommand(); 
     cmd1.Connection = con; 
     cmd.Connection = con; 
     for (int i = 0; i < room.Length; i++) 
     { 
      cmd1.CommandText = "select room_availability from rooms where room_num='" + room[i] + "' "; 
      dr = cmd1.ExecuteReader(); 
      while (dr.Read()) 
      { 
       if (dr[0].ToString().Equals("No"))//this is not working 
        flag = 1; 
      } 
      dr.Close(); 
     } 
     Response.Write(flag); 
     if (flag == 0) 
     { 
      for (int i = 0; i < room.Length; i++) 
      { 
       cmd.CommandText = "update rooms set room_availability='No' where room_num='" + room[i] + "'"; 
       cmd.ExecuteNonQuery(); 
       result = 1; 
      } 
     } 
     else 
     { 
      Label2.Text = "Some of the selected rooms are not available. Kindly try again"; 
      Label1.Visible=false; 
     } 
     if (result == 1) 
     { 
      isRoomAvailable = true; 
      Label2.Text = " Room(s) " + Label1.Text + " is/are booked"; 
      Label1.Visible = false; 
     } 
    } 
    else 
     Response.Write("<script>alert('Select a room first.')</script>"); 
} 

回答

0
I would do more of the logic in SQL, this would simplify the code: 

// Create a condition looking like this: room_num IN('1', '2', '3') 
string roomsCondition = "room_num IN (' + Label1.Text.Replace(" ", "', '") + "')"; 

cmd1.CommandText = 
    @"SELECT SUM(CASE WHEN room_availability='Yes' THEN 1 ELSE 0 END) As available, 
    SUM(CASE WHEN room_availability='No' THEN 1 ELSE 0 END) As not_available 
    FROM rooms WHERE " + roomsCondition; 

此查詢返回的可用和非可用房間數。然後應該比使用標誌更容易制定邏輯。

也看看ExecuteScalar方法。它使得它比我上面顯示的查詢更容易:

using (SqlConnection conn = new SqlConnection(connString)) { 
    string sql = "SELECT COUNT(*) FROM rooms WHERE room_availability='Yes' AND " + 
       roomsCondition; 
    SqlCommand cmd = new SqlCommand(sql, conn); 
    conn.Open(); 
    int availableRooms = (int)cmd.ExecuteScalar(); 
    if (availableRooms > 0) { 
     cmd.CommandText = 
      @"UPDATE rooms 
      SET room_availability='No' 
      WHERE availability='Yes' AND " + roomsCondition; 
     cmd.ExecuteNonQuery(); 
    } else { 
     ... 
    } 
} 
+0

嗨....感謝您的回答。但我在這個領域是一個真正的新人,並且找到這個解決方案有點難。有沒有其他更簡單的方法來做到這一點。如果我遵循我的代碼,我會在哪裏出錯? –

+0

其實你只需要我的第二個例子。它通過'(int)cmd.ExecuteScalar();'給出了可用房間的數量。 ExecuteScalar方法返回第一行的第一列。這比'while(dr.Read()){if(dr [0] .ToString()。Equals「No」))flag = 1; ...'!如果你想知道發生了什麼問題,請[debug](http://www.dotnetperls.com/debugging)!在非工作行上設置一個斷點並查看'dr [0] .ToString()'返回的值。 –

相關問題