2011-12-15 79 views
0

我試圖從數組中獲取2個獨特圖像。現在我刷新頁面,直到我得到2個獨特的圖像。這並不理想。我怎樣才能修改這段代碼來取回2個獨特的圖像,而無需刷新頁面,直到頁面出現爲止。從數組中返回2個隨機圖像

我可以在這一層做,或者我需要檢查數據層中的唯一號碼嗎?

Picture dlPicture = new Picture(); 
     DataTable DTPictures = dlPicture.GetRandomPicture(); 
     Picture dlPicture2 = new Picture(); 
     DataTable DTPictures2 = dlPicture2.GetRandomPicture(); 



     // the variables to hold the yes and no Id's for each set 
     string firstNoPicId = ""; 
     string firstYesPicId = ""; 
     string secondNoPicId = ""; 
     string secondYesPicId = ""; 

     foreach (DataRow row in DTPictures.Rows) 
     { 
      firstYesPicId = row["PicID"].ToString(); 
      secondNoPicId = firstYesPicId; 
      FirstPicMemberNameLabel.Text = row["MemberName"].ToString(); 
      FirstPicLink.ImageUrl = "Pictures/" + row["PicLoc"]; 

     } 

     foreach (DataRow row in DTPictures2.Rows) 
     { 
      secondYesPicId = row["PicID"].ToString(); 
      firstNoPicId = secondYesPicId; 
      SecondPicMemberNameLabel.Text = row["MemberName"].ToString(); 
      SecondPicLink.ImageUrl = "Pictures/" + row["PicLoc"]; 

     } 
     if (firstYesPicId != secondYesPicId) 
     { 

      FirstPicLink.PostBackUrl = "default.aspx?yesId=" + firstYesPicId + "&noId=" + firstNoPicId; 
      SecondPicLink.PostBackUrl = "default.aspx?yesId=" + secondYesPicId + "&noId=" + secondNoPicId; 
     } 
     else 
     { 
      Response.Redirect("Default.aspx"); 
     } 
+3

哪裏的.GetRandomPicture()的代碼? – curtisk 2011-12-15 19:27:42

+0

爲什麼`GetRandomPicture`返回一個`DataTable`爲什麼你循環它的行並一遍又一遍地設置相同的變量? – Magnus 2011-12-15 19:34:48

+0

我在代碼中看不到任何東西。 – 2011-12-15 19:36:36

回答

2

也許是更好的解決辦法是將代碼添加到您的datalayer.GetRandomPicture,以確保它不能連續兩次返回相同的圖片?

在這個Picture類中添加一個LastRandomPictureID變量並在查詢中執行'WHERE NOT ID = LastRandomPictureID'(您可能希望使它更穩健以處理只有1張圖片存在的情況)。

4

有兩種非常明顯的方式來處理這個

  1. 添加過載dlPicture.GetRandomPicture(int picID)這將接受一個I​​D,以便它不會返回已經使用picID

  2. 重構代碼,以便它一直循環到secondYesPicId != firstYesPicId

喜歡的東西

secondYesPicId = firstYesPicId; 
while (firstYesPicId == secondYesPicId) 
{ DataTable DTPictures2 = dlPicture2.GetRandomPicture(); 

    foreach (DataRow row in DTPictures2.Rows) 
    { 
     secondYesPicId = row["PicID"].ToString(); 
     SecondPicMemberNameLabel.Text = row["MemberName"].ToString(); 
     SecondPicLink.ImageUrl = "Pictures/" + row["PicLoc"]; 

    } 
} 
0
var rnd = new Random(); 
int randomPicIndex1 = rnd.Next(numOfPictures); 
int randomPicIndex2; 
do { 
    randomPicIndex2 = rnd.Next(numOfPictures); 
} while (randomPicIndex1 == randomPicIndex2); 

然後使用這些索引爲了從您的表中獲得隨機行。

DataRow row1 = DTPictures.Rows[randomPicIndex1]; 
DataRow row2 = DTPictures.Rows[randomPicIndex2];