Datagridview Column events and properties from a textbox

Pankaj tripathi 185 Reputation points
2023-11-08T19:51:44.9066667+00:00

Hi there ,

I have found some code useful for my form here at https://learn.microsoft.com/en-us/answers/questions/1408049/customtextbox . (looks like his problem is very similar to mine as he was initially referring to my code only in the beginning ) . Anyways here is the code

 public partial class CustomTextBox : TextBox
    {      

        private bool useUpper = false;

        public bool UseUpper
        {
            get { return useUpper; }
            set { useUpper = value; }
        }

        public CustomTextBox()
        {
            this.ContextMenuStrip = new ContextMenuStrip();
            // trick to fix the height when you use customtextbox control
            base.AutoSize = false;
            this.BorderStyle = BorderStyle.None;
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            CustomTextBoxWork.AttachEvents(this);
        }

        public const int WM_PASTE = 0x0302;
        public const int WM_CUT = 0x0300;
        public const int WM_COPY = 0x0301;

        // blocks the default cut , copy , paste
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_COPY || m.Msg == WM_CUT || m.Msg == WM_PASTE)
            {
                // DO NOTHING 
            }
            else
            {
                base.WndProc(ref m);
            }
        }

        


        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            CustomTextBoxWork.DetachEvents(this);
        }
    }

    class CustomTextBoxWork
    {
        [ThreadStatic]
        [Obsolete]
        private static Dictionary<Control, Color> originalBackColors;

        // not use originalBackColors 
#pragma warning disable 0612

        public static Dictionary<Control, Color> OriginalBackColors
        {
            get
            {
                if (originalBackColors == null)
                {
                    originalBackColors = new Dictionary<Control, Color>();
                }
                return originalBackColors;
            }
        }
#pragma warning restore 0612

        public static void AttachEvents(TextBox txb)
        {
            txb.KeyDown += Txb_KeyDown;
            txb.LostFocus += Txb_LostFocus;
            txb.ParentChanged += Txb_ParentChanged;
            txb.TextChanged += Txb_TextChanged;
        }

        public static void DetachEvents(TextBox txb)
        {
            txb.KeyDown -= Txb_KeyDown;
            txb.LostFocus -= Txb_LostFocus;
            txb.ParentChanged -= Txb_ParentChanged;
            txb.TextChanged -= Txb_TextChanged;
            if (OriginalBackColors.ContainsKey(txb))
            {
                OriginalBackColors.Remove(txb);
            }
        }

        private static void Txb_ParentChanged(object sender, EventArgs e)
        {
            var txb = (TextBox)sender;
            if (txb.Parent != null)
            {
                OriginalBackColors[txb] = txb.Parent.BackColor;
                txb.BackColor = OriginalBackColors[txb];
            }
        }

        private static void Txb_KeyDown(object sender, KeyEventArgs e)
        {
            var txb = (TextBox)sender;
            if (e.KeyCode == Keys.Escape)
            {
                txb.Text = "";
            }
            if (e.KeyCode == Keys.Enter)
            {
                txb.BackColor = Color.Yellow; 
                Control ctl = txb;
                while (ctl.Parent != null)
                {
                    var next = ctl.Parent.GetNextControl(ctl, true);
                    if (next != null)
                    {
                        next.Focus();
                        e.SuppressKeyPress = true;
                        e.Handled = true;
                        return;
                    }
                    ctl = ctl.Parent;
                }
            }
        }

        private static void Txb_TextChanged(object sender, EventArgs e)
        {
            var txb = (CustomTextBox)sender;
            if (txb.UseUpper && txb.TextLength > 0)
            {
                string prevText = txb.Text;
                string nextText = ToUseUpper(prevText);
                if (nextText != prevText)
                {
                    int selectionStart = txb.SelectionStart;
                    int selectionLength = txb.SelectionLength;
                    txb.Text = nextText;
                    txb.Select(selectionStart, selectionLength);
                }
            }
        }

        private static string ToUseUpper(string text)
        {
            const string space = " ";
            var args = text.Split(space.ToCharArray());
            for (int i = 0; i < args.Length; i++)
            {
                if (!string.IsNullOrWhiteSpace(args[i]))
                {
                    args[i] = char.ToUpper(args[i][0]) + args[i].Substring(1);
                }
            }
            return string.Join(space, args);
        }

        private static void Txb_LostFocus(object sender, EventArgs e)
        {
            var txb = (TextBox)sender;
            if (OriginalBackColors.TryGetValue(txb, out Color originalBackColor))
            {
                txb.BackColor = originalBackColor;
            }
        }
    }
}

I want to make modification to the following code in which when the focus enters the control its backcolor should be changed to anything like golden . so what is the best event focus or enter . Another problem i want to use the above same functionality for my datagridviewtextbox column . Should i have to change anything for using the above exact code in datagridview column .
thanks

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,862 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,466 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. KOZ6.0 5,630 Reputation points
    2023-11-09T02:37:38.2266667+00:00

    so what is the best event focus or enter.

    The GotFocus event is better because the background color is restored in the LostFocus event.In the case of a Leave event, it becomes an Enter event.

    GotFocus/LostFocus event is Occurs when the application becomes active/inactive.At that time, the Enter/Leave event will not occur.

    Should i have to change anything for using the above exact code in datagridview column.

    Some properties will need to be overwritten with DataGridViewCellStyle values.Below is the source.

    https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/DataGridViewTextBoxEditingControl.cs#131