分かりやすく、使いやすく。

テキストボックスやボタンの文字列の色を変更する方法

スポンサーリンク

ASP.NET(C#)でテキストボックスやボタンの文字列の色を変更するには、各コントロールの ForeColor に System.Drawing.Color で色を設定します。

  1. 文字列の色を変更する方法
  2. 文字列の色を未設定にする方法


文字列の色を変更する方法

次のサンプルコードでは、button1 をクリックするとテキストボックス、ラベル、ボタンの文字列の色を変更します。

aspxファイル(実行可能なサンプルコード)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    <asp:TextBox 
        ID="textBox1" 
        runat="server" 
        Text="テスト文字列" /><br />
    
    <asp:Label 
        ID="label1" 
        runat="server" 
        Text="テスト文字列" /><br />
    
    <asp:Button 
        ID="button1" 
        runat="server" 
        OnClick="button1_Click1" 
        Text="テスト文字列"/><br /> 
C#(実行可能なサンプルコード)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Web.UI;
using System.Drawing;
 
namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected void button1_Click1(object sender, EventArgs e)
        {
            //ラベルの文字列の色を赤にする。
            label1.ForeColor = Color.Red;
 
            //テキストボックスの文字列の色を青にする。
            textBox1.ForeColor = Color.Blue;
 
            //ボタンの文字列の色を緑にする。
            button1.ForeColor = Color.Green;
        }
    }
} 

文字列の色を未設定にする方法

色の設定を解除する場合、System.Drawing.Color の Empty を指定します。

次のサンプルコードでは、 button1 をクリックすると文字列に色を設定し、 button2 をクリックすると設定した色を解除して初期状態に戻します。

aspxファイル(実行可能なサンプルコード)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    <asp:TextBox 
        ID="textBox1" 
        runat="server" 
        Text="テスト文字列" /><br />
    
    <asp:Label 
        ID="label1" 
        runat="server" 
        Text="テスト文字列" /><br />
    
    <asp:Button 
        ID="button1" 
        runat="server" 
        OnClick="button1_Click1" 
        Text="button1"/><br />
    
    <asp:Button 
        ID="button2" 
        runat="server" 
        OnClick="button2_Click1" 
        Text="button2"/><br /> 
C#(実行可能なサンプルコード)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System;
using System.Web.UI;
using System.Drawing;
 
namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected void button1_Click1(object sender, EventArgs e)
        {
            //ラベルの文字列の色を赤にする。
            label1.ForeColor = Color.Red;
 
            //テキストボックスの文字列の色を青にする。
            textBox1.ForeColor = Color.Blue;
 
            //ボタンの文字列の色を緑にする。
            button1.ForeColor = Color.Green;
        }
 
        protected void button2_Click1(object sender, EventArgs e)
        {
            //ラベルの文字列の色を未設定にする。
            label1.ForeColor = Color.Empty;
 
            //テキストボックスの文字列の色を未設定にする。
            textBox1.ForeColor = Color.Empty;
 
            //ボタンの文字列の色を未設定にする。
            button1.ForeColor = Color.Empty;
        }
    }
} 
スポンサーリンク
スポンサーリンク