2011-12-15 41 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];