Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Top Posters

Who's Online (0)

Powered by Vanilla. Made with Bootstrap.
[C#] C# textBox Event to Detect Enter Key (events)
  • C# textBox Event to Detect Enter Key
    Date: Feb. 25, 2010
    By: sunjester

    This is something that new people to C# or programming may not know how to do since they more than likely don't have formal training in programming. Most users of C# that are new or aren't familiar with the language may not even know that it's called an Event. Here we are going to simply add a new event to the textBox control.

    First, add a textBox control to the form. The textBox will be named textBox1 by default. If you double click the textBox control you will automatically generate the code below for that textBox control.


    private void textBox1_TextChanged(object sender, EventArgs e)
    {
    //
    }
    If you look in your Solution Explorer you will see something called Form1.Designer.cs or whatever your form is called. Double click that. You will be presented with a new window. We are going to be adding a KeyPress event to the textBox control. Look at the code below and make your way to the textBox controls section in the code.

    //
    // textBox1
    //
    this.textBox1.Location = new System.Drawing.Point(6, 19);
    this.textBox1.Name = \"textBox1\";
    this.textBox1.Size = new System.Drawing.Size(579, 20);
    this.textBox1.TabIndex = 0;
    this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
    You can see the event we added when we double clicked the textBox control, it is at the bottom this.textBox1.TextChanged. We are going to add our entry below it. How do we know what to enter here? RTFM, no seriously, rtfm. Almost all programming languages have documentation describing everything you need to know. this page, TextBox Members (System.Windows.Forms) will list off members of the textBox class that we are using for our control. If you keep looking you will see one named onKeyPress and right next to that you will see "Raises the KeyPress event", click KeyPress.


    This page will tell you exactly what we are going to do. Below is the code to plugin to your designer code window.



    this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(keyCheck);
    Now, back in your textBox code, you will need the keyCheck method that we passed to the new event.
    private void keyCheck(object sender, KeyPressEventArgs e)
    {
    if (e.KeyChar == (char)13)
    {
    MessageBox.Show(\"Enter was pressed\", \"keypress event\");
    }
    }
    Maybe you want to handle more than one entry? Try throwing down a switch on the key character.

    switch (e.KeyChar)
    {
    case (char)13:
    MessageBox.Show(\"Enter was pressed\", \"keypress event\");
    break;
    }
  • ikaw
    Posts: 25
    hmm.. nice tut!

    In vb.net,

    (e.KeyChar = Chr(13))

    am I right?