在运行时显示随机图像

时间:2009-05-18 06:59:05

标签: c# asp.net

我正在尝试显示随机图像

继承我的代码


private void Page_Load(object sender, EventArgs e)
{
   int num1=0;
   Random randNum = new Random();
   num1 = randNum.Next(0, 9);
   Image1.ImageUrl = DisplayNumber(num1);
   Image1.Visible=true;
}

protected  string DisplayNumber(int i)
{
        string imagepath="";
        switch (i)
        {
            case 0:
                imagepath = "~/fordoctor/doctor_login/images/0.GIF";
                break;

            case 1:
                imagepath = "~/fordoctor/doctor_login/images/1.GIF";
                break;

            case 2:
                imagepath = "~/fordoctor/doctor_login/images/2.GIF";
                break;

            case 3:
                imagepath = "~/fordoctor/doctor_login/images/3.GIF";
                break;

            case 4:
                imagepath = "~/fordoctor/doctor_login/images/4.GIF";
                break;

            case 5:
                imagepath = "~/fordoctor/doctor_login/images/5.GIF";
                break;

            case 6:
                imagepath = "~/fordoctor/doctor_login/images/6.GIF";
                break;

            case 7:
                imagepath = "~/fordoctor/doctor_login/images/7.GIF";
                break;

            case 8:
                imagepath = "~/fordoctor/doctor_login/images/8.GIF";
                break;

            case 9:
                imagepath = "~/fordoctor/doctor_login/images/9.GIF";
                break;
        }
        Session["num1"] = imagepath;
        return imagepath;

    }

但它什么都没显示 我甚至使用Response.Write(Session [“num1”]。ToString());检查了图像。 并且图像将显示在下一页

2 个答案:

答案 0 :(得分:3)

我建议你的代码与此类似:

private void Page_Load( object sender, EventArgs e ) {
    string imgUrl = GetRandomImageUrl();
    Session["num1"] = imgUrl;
    Image1.ImageUrl = imgUrl;
    Image1.Visible = true;
}

protected string GetRandomImageUrl() {
    Random r = new Random();
    return String.Format( "~/fordoctor/doctor_login/images/{0}.gif", r.Next( 0, 9 ) );
}

答案 1 :(得分:0)

检查你的GIF的情况,应该是小写的(通常)。