none
Adding Text to a Label Using Key Press Event C#

    Question

  • I have a Windows Form, with a Label in it.

    I am trying to write in the label the keys I am pressing, so I subscribed to the key press event.

    The code below only allows me to write the first character I press, and I can't seem to implement a cycle that allows me to see every character I press in the label.

    Thanks

    namespace Tutorial5Winforms
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
           
            private void Form1_KeyPress(object sender, KeyPressEventArgs e)
            {
    
                label1.AutoSize = true;
    
                label1.Text = e.KeyChar.ToString();
            }
        }
    }
    
    namespace Tutorial5Winforms
    {
        static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
    }
    Thursday, May 14, 2009 11:22 PM

Answers

  • Use += instead of = to add to the end of the label's Text.

    Note that you will probably have to set label1.Text to "" early (such as in Form_Load event) or in the visual designer so that the label is initially empty.

    Here is an example that also implements backspace.  Other control characters (such as Enter) are ignored.

            private void Form1_Load(object sender, EventArgs e)
            {
                label1.Text = "";
                label1.AutoSize = true;
            }
    
            private void Form1_KeyPress(object sender, KeyPressEventArgs e)
            {
                if (e.KeyChar == '\b') // Backspace
                {
                    if (label1.Text != "") // Are there any characters to remove?
                        label1.Text = label1.Text.Substring(0, label1.Text.Length - 1); // Remove last character?
                }
                else if (!Char.IsControl(e.KeyChar)) // Ignore control chars such as Enter.
                {
                    label1.Text += e.KeyChar.ToString(); // Append this key char.
                }
            }


    Thursday, May 14, 2009 11:45 PM