Start New Discussion within our Software Development Community

Hi,
Can you please take a look at following code and let me know how I can restrict the "txtColor.Text" in a way that if user insert a wrong hex sting(value) like "KKKKKK" the exception handler handle the issue and pops a warning message to correct the input?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SimpleColorPicker
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
  
private void txtColor_TextChanged(object sender, EventArgs e)
        {
            if (txtColor.Text == "")
            {
                lblColor.ForeColor = System.Drawing.Color.MediumPurple;
            }
            else
            {
                string cc = String.Format("#{0}", txtColor.Text);
                Color col = System.Drawing.ColorTranslator.FromHtml(cc);
                lblColor.ForeColor = col;
                lblColor.Refresh();
            }
        }
    }
}

Thanks

You can subscribe to a KeyPress event of textbox control, and use this code:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')
                e.Handled = !System.Uri.IsHexDigit(e.KeyChar);
        }

Or TextChanged event:

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string item = textBox1.Text;
            int n = 0;
            if (!int.TryParse(item, System.Globalization.NumberStyles.HexNumber, System.Globalization.NumberFormatInfo.CurrentInfo, out n) &&
              item != String.Empty)
            {
                textBox1.Text = item.Remove(item.Length - 1, 1);
                textBox1.SelectionStart = textBox1.Text.Length;
            }
        }
This article has been dead for over six months. Start a new discussion instead.