通过随机数asp.net设置颜色

时间:2013-01-09 05:13:10

标签: c# asp.net html

我有一种获取随机颜色的方法:

 private System.Drawing.Color GetRandColor()
    {
        Random r = new Random(DateTime.Now.Millisecond);

        System.Drawing.Color[] colours = 
        {
            System.Drawing.Color.Yellow, 
            System.Drawing.Color.LightGreen, 
            System.Drawing.Color.LightCyan,
            System.Drawing.Color.LightSalmon,  
            System.Drawing.Color.LightSkyBlue
        };

        int i = r.Next(0, colours.Length - 1);

        System.Drawing.Color c = colours[i];

        return c; 
    }

所以我想做的是在页面加载时将这种随机颜色传递给我的html。 所以它将以某种方式放在Page_Load中:

 protected void Page_Load(object sender, EventArgs e)
    {
              // code to set button color 
    } 

<asp:Button ID="Button1" runat="server" Text="Button" BackColor=GetRandColor()/>

2 个答案:

答案 0 :(得分:3)

您可以在C#代码中更改按钮的背景颜色。请检查方法。

private void GetRandColor()
    {
        Random r = new Random(DateTime.Now.Millisecond);

        System.Drawing.Color[] colours = 
        {
            System.Drawing.Color.Yellow, 
            System.Drawing.Color.LightGreen, 
            System.Drawing.Color.LightCyan,
            System.Drawing.Color.LightSalmon,  
            System.Drawing.Color.LightSkyBlue
        };

        int i = r.Next(0, colours.Length - 1);

        System.Drawing.Color c = colours[i];

        Button1.BackColor = c;
    }

答案 1 :(得分:0)

您可以将方法作为常用方法

private void GetRandColor(object sender)
{
    Random r = new Random(DateTime.Now.Millisecond);

    System.Drawing.Color[] colours = 
    {
        System.Drawing.Color.Yellow, 
        System.Drawing.Color.LightGreen, 
        System.Drawing.Color.LightCyan,
        System.Drawing.Color.LightSalmon,  
        System.Drawing.Color.LightSkyBlue
    };

    int i = r.Next(0, colours.Length - 1);

    System.Drawing.Color c = colours[i];

    Button btn = (Button)sender; 
    btn.BackColor = c;
}