How to run code when hitting enter in a c# text box - c#

I'm using web forms
Right now my code runs when I leave the text box and the text has changed. I am running into issues. If I change the text but hit a button instead of enter, it resets via code. I need to be able to change the text and click a button which wont yet do anything, or change the text and hit enter which will trigger code.
thanks for the help
This is text changed event for the text box with notations of what im needing to do. really what I think I need is an event for clicking enter, not changing text
protected void txtboxPlate_TextChanged(object sender, EventArgs e)
{
if (txtboxPlate.Text == "plate number")
{
//will check database for "plate number" and do stuff on enter.
}
else
{
resetforms();// on enter
}
else
{
the text has changed by user, but has clicked a button and needs nothing to happen because of this text change
}
}

You need to implement a method for the KeyDown event of your textbox.
private void txtboxPlate_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter) {
//Code
}
}

Keydown is a client-side event, as far as I know you're more than likely going to have to use JavaScript/Jquery.
Refer to the following link:
Textbox Keydown Event
I would of used a comment but... rep issues :/
edit:
To anyone that hasn't realised yet, the question changed to webforms not winforms
Alternative:
Use a button.
You could place a button next to the textfield, it's simple and not a lot of work goes into it. You can set the TabIndex of the textbox to 1 and the TabIndex of the button to 2 so when you hit TAB it will focus the textbox and if pressed again it will focus the button. You could also look into adding the button to the textbox for design purposes.
edit: You also need to think about post back, when you hit a button the page get's post back meaning values are lost, to persist the data within the field you would have to use view state, session variables or a hidden field. For simplicity I'd set the value of the text box to a hidden field and then simply re-apply the value on page_load. If the value needs to persist across multiple postbacks/accessed from other pages use session variables.
So as a code example:
Remove the Text_changed event entirely.
protected void btnDoStuff(object sender, EventArgs e)
{
if(txtPlateNumber.Text == "Plate Number")
{
//Do stuff
}
else
{
//Do other stuff
}
}
-
If you notice the value disappearing after the post back do something like:
protected void btnDoStuff(object sender, EventArgs e)
{
if(txtPlateNumber.Text == "Plate Number")
{
//Do stuff
myHiddenField.Value == txtPlateNumber.Text;
}
else
{
//Do other stuff
}
}
then reset the value on page_load.

If this is winform and you still want to use textchanged you can try catching your code first for example:
protected void txtboxPlate_TextChanged(object sender, EventArgs e)
{
//Catching code
if (txtboxPlate.Text != "")
{
if (txtboxPlate.Text == "plate number")
{
//will check database for "plate number" and do stuff on enter.
}
else
{
resetforms();// on enter
}
}
else
{
the text has changed by user, but has clicked a button and needs nothing to happen because of this text change
}
cause what textchanged is doing is unless txtboxPlate.Text equels "plate number" it will always do the else statement. Correct me if i'm wrong though but i had the same problem before which almost made me go insane.
Or try above 1 upvote code:
protected void txtboxPlate_TextChanged(object sender, EventArgs e)
{
//Event only happens if you press enter
if (e.KeyCode == Keys.Enter)
{
if (txtboxPlate.Text == "plate number")
{
//will check database for "plate number" and do stuff on enter.
}
else
{
resetforms();// on enter
}
}
else
{
the text has changed by user, but has clicked a button and needs nothing to happen because of this text change
}
}

Related

C# TextBox Change Event in DataGridView

I have a DataGridView with several columns of TextBoxes. I need to capture the event where they are done entering data, and are exiting the box (via Tab, Enter, Mouse click elsewhere, etc)
I have searched SO and Google, and it seems like you have to build an event from scratch. I've tried multiple variations on what I have found since I can't seems to find one that fits with my particular needs.
I've been at this for longer than I care to admit and I need help.
Here is what I have...
// Select DataGridView EditingControlShowing Event
Private void gridData_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) {
e.Control.TextChanged += new EventHandler(textBox_TextChanged);
Control cntObject = e.Control;
cntObject.TextChanged += textBox_TextChanged;
}
// TextBox TextChanged Event
Private void textBox_TextChanged(object sender, EventArgs e) {
// Checks to see if the AddlQty field was altered
if (gridData.Columns[e.ColumnIndex].Name == "AddlQty") {
// Validate Entry
if (e.Text is Not numeric) {
MessageBox.Show("Entry Not Valid, Only Numeric Values Accepted");
} else {
CalcFinalQty(e.RowIndex);
}
}
}
For the record, the code does NOT work, the validation is quasi code and I'm getting an error in the function heading. The important part for me is the
if (gridData.Columns[e.ColumnIndex].Name == "AddlQty"){ }
I just need help getting to that point.

Selection of all of the content of TextBox is not working as expected in WPF

Im having troubles with Selecting All content inside of a TextBox.
Ussually by pressing enter I'm jumping from one textbox to another, because there are like 6-7 TextBoxes below each other
in my Grid, and by pressing enter I need to jump from one to another,
private void Grid_PreviewKeyDown_1(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
UIElement element = e.Source as UIElement;
element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
//TextBox tb = (sender as TextBox);
//if (tb != null)
//{
// tb.SelectAll();
//}
}
}
And while I'm on some of them when I press Enter I'm doing some calculation like this:
private void txt2_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
try
{
CalculateSomethingFromOtherTextBoxes();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
My Question is next: When I jump from each other and when I finish calculation (enter is pressed), the next TextBox I will jump to I would like SELECTALL of TextBox's content when I jumped on it.
In case I want to edit some value or whatever, and it is confusing sometimes content insidee is selected and sometimes it is not.
I tried setting GotFocus event on each of TextBoxes and It looks like this:
private void txt3_GotFocus(object sender, RoutedEventArgs e)
{
txt3.SelectAll();
}
But unfortunately somehow this is sometimes working sometimes it is not, I mean all of content is selected sometimes and sometimes it is not..
Thanks guys
Cheers
Try to handle the GotKeyboardFocus event instead of the GotFocus event. This should work:
private void txt3_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
txt3.SelectAll();
}
There is no property that you can set to select all of the Text in a TextBlock or TextBox. Selecting all text must be accomplished using the TextBoxBase.SelectAll Method. What you could do in a Style is to set an event handler for the GotFocus event, where the handler code would call SelectAll, but your handler would of course need to be in code and not XAML.
One other possibility would be for you to create an Attached Property that would select the text whenever the TextBox gets focus, but again it's not possible to do this in XAML.

Determining the type of Event that was raised on List Box, Selected Index Change. C#

I understand that there are Listbox Select index change questions floating around. However, this question focuses on a different matter. I have a list box, with some strings on the form. What I am trying to accomplish is to be able to scroll through the items in the list box (i.e using the arrow keys to navigate to a particular item). Once I navigate to the item I want, I want to either be able to press enter on the item and continue my application. So, the question is How to determine the Event type of that was raised on the List box in order to compare the event with either a Mouse Click event or a Keydown event, thus allowing me to decide which conditional statement to execute based of the result of the boolean expression......The reason I need to determine the type is because if the user presses ENter on the selectedIndexed Item a Dialogbox Appears, currently the dialogbox appears everytime a user HIGHLIGHTS a new item (you can see how that is a problem).
Psuedo Code
if (Listbox_Selected_Event_EventType isEqualTo Mouse_Click)
{
// execute code
} else if (Listbox_Selected_Event_EventType isEqualTo KeydownEvent)
{
// execute code
}
Finished code thanks to Evan,
private void listBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
if (e.KeyChar == (char)Keys.Return)
{
var file = Directory.GetFiles(urlHistoryFolder, listBox1.Text).FirstOrDefault();
String line;
try
{
using (StreamReader sr = new StreamReader(file))
{
line = sr.ReadToEnd();
}
DialogResult result1 = MessageBox.Show("Are You sure you want to Load this WebService", "Important Question", MessageBoxButtons.YesNo);
if (result1 == DialogResult.Yes)
{
//MessageBox.Show("Loading WebService");
textEndPointUri.Text = line;
listBox1.Visible = false;
GetBtn_Click(sender, e);
}
}
catch (Exception exp)
{
Console.WriteLine("File could not be read:");
Console.WriteLine(exp.Message);
}
}
}
}
The problem is you are looking at the wrong event. You should be handling the MouseClick event and the KeyUp or KeyDown event on the list box.
private void listBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Get the selected item and do whatever you need to it
//Open your dialog box
}
}
private void listBox1_Click(object sender, MouseEventArgs e)
{
//Get the selected item and do whatever you need to it
//Open your dialog box
}
Then there is no need for a conditional as you have handled both the events individually. Make sure you remove your Dialog box code from the SelectedIndexChanged event.
EDIT:
SelectedIndexChanged fires every time you select and item in the ListBox Object. The box still stores an index even if you don't handle that event. So you can reference or manipulate the PROPERTY of SelectedIndex anywhere. If you handle the two above events, any time a user clicks an item or presses enter you check if there is a selected item:
if (listBox1.SelectedIndex != -1)
{
//Now we know you have an item selected
//Do some stuff
}
Add a Button to the Form and set the AcceptButton() Property of the FORM to that Button. Now when Enter is pressed the Button will fire. Display your dialog in the Button Click() handler. This has the added benefit that people can also click the Button instead of pressing Enter:
private void button1_Click(object sender, EventArgs e)
{
if (ListBox.SelectedIndex != -1)
{
// ... display the dialog ...
Console.WriteLine(ListBox.SelectedItem.ToString());
}
}
To identify if ENTER has been pressed:
private void listBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
// do something
}

c# Listbox control (arrows and enter keys)

I have a listbox which displays the contents of an array. The array is populated with a list of results when my "go" button is pressed.
The go button is set as the AcceptButton on the form properties so pressing the Enter key anywhere in the focus of the form re-runs the go button process.
Double clicking on a result from the array within the listbox works fine using below:
void ListBox1_DoubleClick(object sender, EventArgs e) {}
I would like to be able to use my arrow keys and enter keys to select and run an event without having to double click on the line within the listbox. (however go button runs each time instead)
Basically open the form, type search string, press enter to run go button, use up and down arrows then press enter on selection to run same event as double click above. Will need to change focus after each bit.
You can handle the KeyDown events for the controls you want to override. For example,
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//execute go button method
GoButtonMethod();
//or if it's an event handler (should be a method)
GoButton_Click(null,null);
}
}
That will perform the search. You can then focus your listbox
myListBox.Focus();
//you might need to select one value to allow arrow keys
myListBox.SelectedIndex = 0;
You can handle the Enter button in the ListBox the same way as the TextBox above and call the DoubleClick event.
This problem is similar to -
Pressing Enter Key will Add the Selected Item From ListBox to RichTextBox
Certain controls do not recognize some keys when they are pressed in Control::KeyDown event. For e.g. list box does not recognize if the key pressed is Enter key.
See the remarks section of the Control::KeyDown event reference.
One way to resolve your problem might be writing a method for the Control::PreviewKeyDown event for your list box control:
private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up && this.listBox1.SelectedIndex - 1 > -1)
{
//listBox1.SelectedIndex--;
}
if (e.KeyCode == Keys.Down && this.listBox1.SelectedIndex + 1 < this.listBox1.Items.Count)
{
//listBox1.SelectedIndex++;
}
if (e.KeyCode == Keys.Enter)
{
//Do your task here :)
}
}
private void listBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Enter:
e.IsInputKey = true;
break;
}
}

Problem with button when text entered into the textbox

I am trying to make the save button visible when text is entered into the text box by using the following code:
if (tbName.TextModified == true)
{
btnCTimetablesOk.Visible = true;
}
else
{
btnCTimetablesOk.Visible = false;
}
but it gives error at tbname.textmodified
is there any other way to visible the button when we enter the text in text box
this is error i am getting "the event textbox.textmodified can only appear on the left hand side of += or -="
Try using the textbox's Enter and Leave events to show/hide your button:
private void textBox1_Enter(object sender, System.EventArgs e)
{
btnCTimetablesOk.Visible = true;
}
private void textBox1_Leave(object sender, System.EventArgs e)
{
btnCTimetablesOk.Visible = false;
}
Then modify your textbox to use these new methods.
If I'm reading your text correctly, you want the save button to be visible when the textbox has text in it and invisible when the text box is blank. If that's the case, you can use the Leave event (which occurs when the textbox loses focus) and a simple if statement:
private void textBox1_Leave(object sender, System.EventArgs e)
{
if(textBox1.Text != "")
btnCTimetablesOk.Visible = true;
else
btnCTimetablesOk.Visible = false;
}
You can also put this conditional block in any other methods kicked off by events that change the text of the box.
Also, you might want to consider using Enabled instead of Visible, it'll leave the button on the form but will gray out the text and clicking will do nothing.
I'm going to take a stab in the dark here and assume that the button is related to the textbox and you probably want someone to be able to type something in the textbox then click the button. You probably don't want the user to have to type something, then tab out or click somewhere else to make the button visible then click the button.
tbName_TextChanged(object sender, EventArgs e)
{
btnCTimetablesOk.Visible = !String.IsNullOrEmpty(tbName.Text)
}
Btw you're getting that error because TextModified isn't a boolean property, it's an event, like TextChanged or Leave or Enter. You can assign an event handler to it but you can't just check it like that.
As an aside I personally hate systems hungarian for winforms controls. I'd much rather have a timetablesOkButton than a btnCTimeablesOK button. That way if you also have a timetablesNameTextBox you can see at a glance that the button and the textbox match. Of course it may not be up to you.

Categories

Resources