Click here to Skip to main content
15,891,754 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have a program created in Visual Studio 2017 / C# / Sql Server(Database). I have several textboxes named firstname, middlename and lastname. How can I proceed into midlename textbox after I input data into the firstname textbox and press enter.

What I have tried:

Any help would be appreciated. Thankyou so much.
Posted
Updated 17-Jul-17 9:56am
Comments
londhess 17-Jul-17 8:11am    
You can used jQuery event

$(document).keypress(function(e) {
if(e.which == 13) {
$(document.activeElement).next().focus();
}
});
Afzaal Ahmad Zeeshan 17-Jul-17 9:05am    
How are you so sure that he wants to do ASP.NET programming?
Member 13296680 17-Jul-17 8:35am    
okay, I'll try using it. thank you so much
Afzaal Ahmad Zeeshan 17-Jul-17 9:05am    
Can you tell the framework, which you are using — ASP.NET, or WinForms etc?
Member 13296680 17-Jul-17 9:35am    
I'm using winforms

Your project is Web or not? If you're on desktop apps you can try this (inside KeyDown event):
C#
if (e.KeyData == Keys.Enter)
{
    e.SuppressKeyPress = true;
    SelectNextControl(YOUR_CONTROL_HERE, true, true, true, true);
}

If your project is web the londhess' solution is good.
 
Share this answer
 
Quote:
Dave K. wrote: "By using ENTER to move from field to field, you are going against the standard functionality of Windows applications."
I respectfully disagree with this statement in the sense that I think it is too generalized, too absolute.

There are many scenarios where an application controls the focus of user interaction from Control to Control according to some set of rules, or, in sequential order. A "wizard" is a good example.

The designers of Windows Forms allow any Control to be removed from being a TabStop by simply setting a property. For TextBox and RichTextBox, both offer Control over whether Tabs are accepted, and the TextBox allows you to ignore Enter.

These options, I believe, are there for a reason: to enable developers to have flexibility for designing application behavior.

Now, let me show you a fairly complete sketch (that means it works in VS 2017) for a WinForm UserControl that manages the users data entry in sequence through six TextBoxes. This UserControl has two Buttons, 'btnSubmit, and 'btnCancel..

All Controls in the UserControl have their TabStop property set to 'false. The TextBoxes have both AcceptsTab, and AcceptsReturn properties set to false.

All key-entry on the UserControl is intercepted by over-riding ProcessCmdKey.

Validators are attached to the first three TextBoxes: the first requires at least one digit to complete; the second requires 2 digits and 2 punctuations to complete; the third requires some text entry of any type. The other three TextBoxes have a default validator defined that accepts anything, or no text.

When the user reaches the last TextBox, if there is no validation error, the Submit Button is enabled.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MatrixTestForm
{
    public partial class DataEntryUserControl : UserControl
    {
        public DataEntryUserControl()
        {
            InitializeComponent();
        }

        public Action<List<string>> SendData;
        
        public Dictionary<TextBox,Func<TextBox, bool>>  TxtBxesToValidator = new Dictionary<TextBox, Func<TextBox, Boolean>>();

        private bool allValid = false;

        private List<TextBox> textBoxes = new List<TextBox>();
        private TextBox activeTextBox;
        private int lastTBoxIndex;
        
        private void DataEntryUserControl_Load(object sender, EventArgs e)
        {
            btnSubmit.Enabled = false;
            
            textBoxes.AddRange(new List<TextBox>()
            {
                textBox1, textBox2, textBox3, textBox4, textBox5, textBox6
            });

            lastTBoxIndex = textBoxes.Count - 1; // adjust for #0 offset

            foreach (var tbx in textBoxes)
            {   
                tbx.Enter += TbxOnEnter;
                tbx.Leave += TbxOnLeave;
            }
            
            activeTextBox = textBox1;
            textBox1.Capture = true;

            // no digits
            toolTip1.SetToolTip(textBox1, "no digits");
            TxtBxesToValidator[textBox1] = box =>
            {
                return box.Text != null && !box.Text.Any(char.IsDigit);
            };

            // must have 2 digit2 and 2 punctuation
            toolTip1.SetToolTip(textBox2,"2 digits, 2 ounctuation");
            TxtBxesToValidator[textBox2] = box =>
            {
                return box.Text != null
                       && box.Text.Any(char.IsDigit)
                       && box.Text.Where(char.IsDigit).Count() == 2
                       && box.Text.Any(char.IsPunctuation)
                       && box.Text.Where(char.IsPunctuation).Count() == 2;
            };

            // gotta have something
            toolTip1.SetToolTip(textBox3, "enter something");
            TxtBxesToValidator[textBox3] = box =>
            {
                return !String.IsNullOrWhiteSpace(box.Text);
            };
        }
        
        private void TbxOnEnter(Object sender, EventArgs eventArgs)
        {
            activeTextBox = sender as TextBox;
            activeTextBox.Capture = true;
        }

        private void TbxOnLeave(Object sender, EventArgs eventArgs)
        {
            activeTextBox.Capture = false;
            activeTextBox = null;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Enter && activeTextBox != null)
            {
                activeTextBox.Capture = false;
                
                // validator

                if (TxtBxesToValidator.ContainsKey(activeTextBox))
                {
                    allValid = TxtBxesToValidator[activeTextBox](activeTextBox);      
                }

                if (! allValid)
                {
                    btnSubmit.Enabled = false;
                    MessageBox.Show("invalid");
                    return base.ProcessCmdKey(ref msg, keyData);
                }

                int ndx = textBoxes.IndexOf(activeTextBox);

                if (ndx == lastTBoxIndex)
                {
                    btnSubmit.Enabled = allValid;
                }
                else
                {
                    textBoxes[ndx + 1].Focus();
                    textBoxes[ndx + 1].Capture = true;
                }

                return true;
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            btnSubmit.Enabled = false;
            
            // whatever : hide the UserControl ?
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            // send the valid data back to wherever ?
            SendData?.Invoke(textBoxes.Select(tbx => tbx.Text).ToList());
            
            // clean-up
            // hide the UserControl ?
            // clear the TextBoxes ?
            // other ??
        }
    }
}
 
Share this answer
 
Comments
Dave Kreskowiak 17-Jul-17 16:14pm    
I come from the perspective where data entry is everything.

Here, and most other apps we've used, the standard is tab between fields and ENTER to submit. I don't see too many apps (650+ apps running around here) doing it the other way around.

But, that's just my perspective. :)
BillWoodruff 17-Jul-17 17:32pm    
Our experiences differ, brother Dave :) It may interest you to note that the code example shown does not restrict the user to sequential entry: nothing prevents the user from using the mouse to select any of the TextBoxes to type into (of course, that could be implemented).

I bet you have no problem writing "guard clauses" in your event handlers to avoid letting errors propagate, test for nulls, etc. Why shouldn't the same principle apply in UI design ?

Note that in this example I did not use ErrorProvider; usually I would.
Dave Kreskowiak 17-Jul-17 17:36pm    
Mine was a simple example for a starting point, that's all. Unless I missed something?
By using ENTER to move from field to field, you are going against the standard functionality of Windows applications. ENTER is considered as the Submit button for a form, not move to the next field.

But, it is possible with Control.SelectNextControl()[^].

I haven't used it but after looking at the documentation, I would probably make a custom TextBox control (create a new class and derive from TextBox) and override its OnKeyDown method for a start:
C#
private override void OnKeyDown(KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        e.Handled = true;
        e.SuppressKeyPress = true;

        Parent.SelectNextControl(this, true, true, true, true);
    }
    else
    {
        base.OnKeyDown(e);
    }
}

WARNING!!
In order for this to work, the parent Form can NOT have it's AcceptButton property set. It must be "(none)".
 
Share this answer
 
Below code you use for this.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
SendKeys.Send("{Tab}");
}

please set tab order in sequence for textboxes.
 
Share this answer
 
Comments
Dave Kreskowiak 17-Jul-17 10:30am    
You should NEVER use SendKeys for anything like this at all.
Atlapure Ambrish 17-Jul-17 13:53pm    
And what is the issue??
Dave Kreskowiak 17-Jul-17 14:17pm    
Your use of SendKeys is unreliable as it sends keystrokes to whatever window has the focus, which MAY NOT be the application you intend.
Atlapure Ambrish 19-Jul-17 7:28am    
The question was to move focus to another control on pressing enter key and this is the easy and quick solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900