I am working on a silverlight app that you need to enter information into a textbox and then just hit enter. Well there is no onclick event, that I could find, so what I did was use the onkeypressup event and check if it was the enter key that was pressed if so do "blah".
It just feels like there is a better way to do this. So the question is, is there?
I thinks that's the way to catch Key.Enter.
Also, you're code will be more readable if you use the KeyDown event instead of the KeyUp event.
If you only care about catching Key.Enter for a single control then your approach is correct.
You can also catch the Key.Enter for a group of related controls by using the KeyDown event of their container ("Event Bubbling").
Do you really want it in the textbox? I would put a onkeyup handler on the container (e.g. Grid, Canvas) to press the button anywhere on the form.
This will work if you use want to bind the Command property instead of using the Click event. Start by creating an event handler for Click (see below) and then in the KeyUp do:
private void MyTextBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter) SomeButton_Click(this, null);
}
private void SomeButton_Click(object sender, RoutedEventArgs e)
{
ICommand cmd = SomeButton.Command;
if (cmd.CanExecute(null))
{
cmd.Execute(null);
}
}
I use the following implementation when using the command pattern:
private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
BindingExpression b = MyTextBox.GetBindingExpression(TextBox.TextProperty);
if (b != null)
b.UpdateSource();
ICommand cmd = SomeButton.Command;
if (cmd.CanExecute(null))
cmd.Execute(null);
}
}
When you press Enter, the data source of the textbox is not updated and the command uses an old value. Therefore you have to call UpdateSource before executing the command.
Of course you can catch the event on a higher level than the textbox.
Well, Im preaty new to Silverlight and I created HitEnter beahaviour for button which have one DependencyProperty Button.
And I manulay wire up Button and Behavior (in code behind) and then when enter is hit I inovke the command on the button.
Related
Here's what i want to do:
I want to be able to take the contents entered into a textbox. Once the user hits the ENTER key or the enter button I made, to have that content appear in a label I've placed on my form.
And have that same label change to whatever you enter in the textbox everytime you hit enter.
I hope I explained this good enough. Thanks!
Subscribe to KeyDown event of TextBox and check if Enter is pressed
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
label1.Text = textBox1.Text;
}
add a button to your form, double click it, inside the event add the code below
label1.text=textbox1.text
and do some basic tutorials, dude
Assuming you are using winforms... First you need to enssure that your form will response to keyboard events.
So you need to set the property KeyPreview to true.
Then use the event KeyDown and write this code:
private void form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
myLabelName1.Text = myTextBoxName1.Text;
}
I have 10 buttons, 0-9 (button0, button1, button2...). When I click any of these buttons, I would like to perform the same routine on them. I would like to know how to, upon clicking of any of these buttons, direct them to the routine below.
private void button0_Click(object sender, EventArgs e)
{
int newValue;
newValue = Convert.ToInt32(Button.text);
}
I have already gone into the properties of each button, then events, and changed the click event to button0_Click (I would have thought this would add "handles button1.click, button2.click, etc." after "private void button0_Click(object sender, EventArgs e)" but if it does that in the background, that's ok as long as it works.)
I also need to know how to identify the button that has been pressed, which is where I'm at with "Convert.ToInt32(Button.text)" (e.g. button2.text = "2").
You can select the same event handler for all the buttons in the designer (in the event tab of the properties window, select the event and there'll be a drop down with all your defined event handlers).
To get which button has been clicked on, cast the sender argument to a Button and you'll have it.
Button button = (Button)sender;
int value = int.Parse( button.Text );
Edit: Also, the "Handles control.event" syntax only exists in Visual Basic.
Edit: Check out the generated code (Form1.Designer.cs, for example) to see how the events are hooked up.
The C# language doesn't use handles to bind events (as VB does). The code for the actual binding is in the generated code for the form, i.e. in the background as you put it.
The sender property is a reference to the control where the event happened. You just need to cast it to the actual type of the control:
private void button0_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
int newValue = Convert.ToInt32(button.text);
}
As an alternative to using the text of the button (for example if you want to translate the application to different languages, or simply don't want to rely on the text), you can put whatever you like in the Tag property of each button, and retrieve it in the event handler.
You could wire them all up to the same event handler an extract the button from sender e.g.
private void button0_Click(object sender, EventArgs e)
{
var button = sender as Button
if (button != null)
{
int newValue = Convert.ToInt32(Button.text);
}
}
There are a button and a textbox. I added a "KeyDown" event to textbox so that when "enter" is pressed button gets clicked. Good, then I tried to give focus to textbox again but failed. In the code below I tried three ways but neither is working.
private void txt_addRemove_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
btn_BC_add.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
// 1.way
// IInputElement focusedElement = FocusManager.GetFocusedElement(txt_addRemove);
// 2.way
// Keyboard.Focus(txt_addRemove);
// 3.way
// txt_addRemove.Focus();
}
}
Add this
if (!textBox1.Focus())
{
textBox1.Focus();
}
What this does:
1. We check if the textbox is NOT focused.
2. If it is not focused, focus the control.
EDIT: How about this:
btn_BC_add.PerformClick()
Try focusing the textbox after the event handler is finished using:
Dispatcher.Invoke(() => { txt_addRemove.Focus(); })
couldnt you also try changing the focus from the button event handler? this might not be desirable if you dont want the focus to be on your textbox after a normal click of the button, but it should work.
Im guessing that your button click is generating a post back before the focus can be changed
I have a tree view on the left side. Selecting a node displays relevant information in a form on the right side.
Would I be able to keep the tree and any one control (textbox, combobox, checkbox) on the right in focus at the same time? This will enable a user to select a field, make a change, select another node, and without having to go back and select the same field again, just type and change the value of the same field.
Thanx.
EDIT
I suppose one could implement such behaviour manually:
private Control __cFocus;
private void {anyControl}_Focus(object sender, EventArgs e)
{
__cFocus = (Control)sender;
}
private void treeView1_AfterSelect(object sender, EventArgs e)
{
__cFocus.Focus();
}
I was just wondering if there exists an automatic / more elegant solution
EDIT 2
Ok, so it seems I'll have to implement it manually. Manual implementation it is then. However, now there seem to be another problem; not sure if I should ask this as a separate question.
When selecting a node the textbox gains focus as intended, but only when using the keyboard. It doesn't work when selecting a node with the mouse. First I thought that it might be a mouse event that's interfering, but stepping revealed that the MouseUp event fired first and then the AfterSelect event which sets the focus, so I don't think it's interfering. The textbox's Enter event is also fired, but for some reason it loses focus again to the tree.
Thanx
no, you cannot keep two controls in focus at the same time. But what you can do is set the focus to the target control in the treeview AfterSelect event
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
textBox1.Focus();
textBox1.SelectAll();
}
then in your textbox leave, save the changes, like so:
private void textBox1_Leave(object sender, EventArgs e)
{
//save changes here
}
this way, everytime you select an item in the treeview, check your textbox for change and save as needed, then you will refocus on the textbox for your next edit
There only can be one element having the focus!
But I have an idea for you that might solve your problem. Assuming you have a window with a TreeView and a TextBox. Set the HideSelection property of the TreeView to false and subscribe the AfterSelect event (like edeperson already answered) like this:
private void OnTreeViewAfterSelect(object sender, TreeViewEventArgs e)
{
textBox1.Text = e.Node.Text;
textBox1.Focus();
}
Then subscribe the KeyDown event of the TextBox and do following in the event method:
private void OnTextBoxKeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Up) || (e.KeyCode == Keys.Down))
{
treeView1.Focus();
SendKeys.Send(e.KeyCode == Keys.Up ? "{UP}" : "{DOWN}");
}
}
At last subscribe the Leave event of the TextBox and do following in the event method:
private void OnTextBoxLeave(object sender, EventArgs e)
{
if (treeView1.SelectedNode != null)
{
treeView1.SelectedNode.Text = textBox1.Text;
}
}
And, voilá it should work like you expected it...
If you want to focus on it , you can use usercontrol. you can put your textbox on usercontrol and set focus of this textbox on usercontrol using set properties on treeview select.
No you may not, only one control may be in focus at any given time.
See Moonlight's comment for one way to achieve the behavior that you seek.
I want to allow the user to send his message when he press enter in the textbox.
I went to search and im using the sample codes below.
Now the problem is when i press enter, the event is triggered more than once like about 4-5 times.
Someone else suggested to use keyup. I have tried keyup, keydown and keypress. All have the same problem.
How do i prevent it from firing the event more than once?
private void tbxAnswer_TextChanged(object sender, EventArgs e)
{
tbxAnswer.KeyUp += new KeyEventHandler(tbxAnswer_KeyUp);
}
private void tbxAnswer_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)13)
{
MessageBox.Show("Hello");
}
}
Thank you!
You are adding the KeyUp event handler multiple times (inside the TextChanged handler); therefore, when Enter is pressed, the handler executes multiple times.
What you want to do here is add the KeyUp handler just once, inside your form's constructor, just after the InitializeComponent() call:
public MyForm()
{
// other code possibly here
InitializeComponent();
// and now add the event handler:
tbxAnswer.KeyUp += new KeyEventHandler(tbxAnswer_KeyUp);
}
private void tbxAnswer_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)13)
{
MessageBox.Show("Hello");
}
}
This is because every time you change the text, the tbxAnswer_TextChanged is called/ fired you assign an action to the keyup event; if the text is changed 4 times then you assigned the keyup event 4 times and it increases every time you change the text.
try this out:
tbxAnswer.KeyUp += new KeyEventHandler(tbxAnswer_KeyUp);
private void tbxAnswer_TextChanged(object sender, EventArgs e)
{
}
private void tbxAnswer_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)13)
{
MessageBox.Show("Hello");
}
}
Change your code to this
tbxAnswer.KeyUp -= tbxAnswer_KeyUp;
tbxAnswer.KeyUp += new KeyEventHandler(tbxAnswer_KeyUp);
In your code snippet, whenever the text of the TextBox changes, another eventhandler is added to the KeyUp handler. You should only add event handlers once (for instance, just after creating the textbox).
Sara and Jon have already provided the correct answer to your specific question. But if you want to go further and get a better understanding of how and when to use any particular key handling event take a look at my article Exploring Secrets of .NET Keystroke Handling. I explain and diagram when and where each event is useful, plus provide a KeystrokeSandbox application that lets you actually watch what happens!