Displaying The Color Name and Showing The Color

Displaying The Color Name and Showing The Color

To display the color name and show the color using C#, we can use the System.Drawing namespace. Here is an example code snippet that takes a color name from the user, and then displays the name and the color in a message box:

using System.Drawing;

using System.Windows.Forms;

namespace ColorDemo

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            string colorName = textBox1.Text;

            try

            {

                Color color = Color.FromName(colorName);

                MessageBox.Show(“Color name: ” + colorName + “\nColor: ” + color.ToString());

            }

            catch (Exception ex)

            {

                MessageBox.Show(“Error: ” + ex.Message);

            }

        }

    }

}

In this example, we first get the color name from a text box. We then use the Color.FromName() method to convert the color name to a Color object. If the color name is valid, the Color object is created successfully, and we can display the color name and the color in a message box. If the color name is not valid, the Color.FromName() method throws an exception, which we catch and display an error message in a message box.

When the user changes the DropDownList, the SelectedIndexChanged event fires and your event handler goes into action. In this routine, you capture the name of the selected color in the variable strColor. Next, you declare the variable objColor as a System.Drawing.Color type so it can hold that type of content.

Converting a color name, such as YellowGreen into a Color type is a little tricky. Inside the System.Drawing namespace is a useful chunk of code called ColorTranslator. One of the capabilities of ColorTranslator (the FromHtml() method) takes a name or value that’s in an HTML format (such as #ff00aa or White) and converts it to a .NET Color.

After you convert the ordinary color name into something that the Panel control understands, you tell the Panel control to use that for its background color (BackColor). As for the Label control, you already have the name of the color, so you instruct the Label to display the name as its Text property.

Apply for ASP.NET Certification Now!!

https://www.vskills.in/certification/certified-aspnet-programmer

Back to Tutorial

Share this post
[social_warfare]
Understanding Namespaces
Built in functions – PHP

Get industry recognized certification – Contact us

keyboard_arrow_up