1

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

 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()/>
4

2 回答 2

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;
    }
于 2013-01-09T05:18:08.280 回答
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;
}
于 2013-01-09T05:34:39.793 回答