[ VB.NET / C# ] システム定義色の文字列から Color オブジェクトを生成 ( Color.FromName )

Pocket

ここでは、C# と VB.NET において、システム定義色を表す文字列から Color オブジェクトを生成するサンプルプログラムを掲載しています。

スポンサーリンク

システム定義色の一覧

システム定義色は KnownColor 列挙体で定義されています。次のサンプルコードでは、システム定義色を表す文字列から Color オブジェクトを生成してデータグリッドビューに列挙して描画しています。

システム定義色一覧

システム定義色一覧

VB.NET

        ' システム定義色の一覧をデータグリッドビューに設定・表示する
        For Each Name As String In [Enum].GetNames(GetType(KnownColor))

            ' 行追加
            Dim idx As Integer = DataGridView1.Rows.Add()

            DataGridView1.Rows(idx).Cells(0).Value = Name ' システム定義色を表す文字列
            ' システム定義色(文字列)から Color オブジェクトを作成
            DataGridView1.Rows(idx).Cells(1).Style.BackColor = Color.FromName(Name)
        Next

C#

        // システム定義色の一覧をデータグリッドビューに設定・表示する
        foreach (string name in Enum.GetNames(typeof(KnownColor)))
        {
            // 行追加
            int idx = dataGridView1.Rows.Add();

            dataGridView1.Rows[idx].Cells[0].Value = name; // システム定義色を表す文字列
            // システム定義色(文字列)から Color オブジェクトを作成
            dataGridView1.Rows[idx].Cells[1].Style.BackColor = Color.FromName(name);
        }

KnownColor 列挙体に定義されているかチェックする

次は、KnownColor 列挙体に文字列が定義されているかを確認するサンプルになります。大文字・小文字は区別されます。

VB.NET

        ' Enum に定義されているか判定する
        ' 大文字・小文字は区別される
        Console.WriteLine([Enum].IsDefined(GetType(KnownColor), "Red"))    ' True
        Console.WriteLine([Enum].IsDefined(GetType(KnownColor), "redred")) '  False

C#

            // Enum に定義されているか判定する
            // 大文字・小文字は区別される
            Console.WriteLine(Enum.IsDefined(typeof(KnownColor), "Red"));    // True
            Console.WriteLine(Enum.IsDefined(typeof(KnownColor), "redred")); // False

スポンサーリンク


Pocket

Leave a Comment

Your email address will not be published. Required fields are marked *