我正试图从阵列中找回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");
}
答案 0 :(得分:4)
有两种非常明显的方法来处理这个
添加重载dlPicture.GetRandomPicture(int picID)
这将接受一个ID,以便它不会返回已经使用过的picID
重新构建代码,使其循环到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"];
}
}
答案 1 :(得分:2)
也许更好的解决方案是在datalayer.GetRandomPicture中添加代码以确保它不能连续两次返回相同的图片?
在这个Picture类中添加一个LastRandomPictureID变量并在你的查询上做一个'WHERE NOT ID = LastRandomPictureID'(你可能想让它更健壮一些,以处理只有1张图片存在的情况)。
答案 2 :(得分: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];