Adding Events To WinForms? - c#

I have a TextBox on a WinForm and I want to execute some code every time someone presses a key inside of that TextBox. I'm looking at the events properties menu, and see the KeyDown event, but don't know how to add code to it.

You need to add an event handler for that event. So in the properties menu, double-click on the field beside the KeyDown event and Visual Studio will create an event handler for you. It'll look something like this:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
// enter your code here
}
You can also subscribe to events yourself without using the Properties window. For example, in the form's constructor:
textBox1.KeyDown += HandleTextBoxKeyDownEvent;
And then implement the event handler:
private void HandleTextBoxKeyDownEvent(object sender, KeyEventArgs e)
{
// enter your code here
}

These answers will have visual studio generate the event and bind it behind the scenes in the Designer.cs file.
If you want to know how to bind events yourself, it looks like this.
MyTextBox.KeyDown += new KeyEventHandler(MyKeyDownFunction)
private function MyKeyDownFunction(object sender, KeyEventArgs e) {
// your code
}
If done this way, the new KeyEventHandler() part is optional. You can also use lambdas to avoid boilerplate code.
MyTextBox.KeyDown += (s, e) => {
// s is the sender object, e is the args
}

Doubleclick the textfield next to it.

I assume you are in Visual Studio. One way would be to double click on the empty textbox on the right of the KeyDown event: VS will generate the code for you.

You need to add a handler to the event.
Double-click the KeyPress event in the textbox's Properties window to make Visual Studio generate an event handler in the code file.
You can then put any code you want to inside the event handler function. You can check which key was pressed by writing e.KeyCode.

Related

How to create click events for different text boxes in visual studio 2015

What I know:
In visual Studio 2015 after double-clicking a button, VS will bring the cursor to generated code inside a "button1_click" event.
If a different button is double-clicked, another (completely separate) "button2_click" event is generated.
The same can be said for a TextBox being double-clicked; the user is brought to a generated event for "textbox1_textChanged" or a textbox2_textChanged."
What I want to know:
When clicking textBox1 in form view, accessing its properties, and clicking "events" and double clicking "Click" at the top, the "textbox1_Click" is generated. (This is good)
However, when clicking a SECOND textbox (textbox2), accessing its properties, Events, and double clicking its "Click" event, it brings the cursor to THE SAME EVENT that was generated for textbox1, aptly named "textbox1_Click." (This is not what I want.)
All I ultimately want is:
textbox1_Click {
textbox1.SelectAll();
}
textbox2_Click {
textbox2.SelectAll();
}
How do I create this SECOND click event for my second textbox (textbox2)?
Is it done with an if statement, possibly using sender or e?
Double-clicking the event name (or the object) automatically adds code to the Designer.cs file for your form. That's how the events are linked to their respective controls.
If your two controls are "double-clicking" to the same event handler [and if such behavior is unintentional], fastest fix is to remove the event wire-up from the second control in Designer.cs and double-click the control again.
Look for this line of code:
this.textBox2.Click += new System.EventHandler(this.textBox1_Click);
Which indicates that your second texbox is wired up to the same event as your first one.
void textbox1_Click(object sender, EventArgs e)
{
textbox2.SelectAll();
}
void textbox2_Click(object sender, EventArgs e)
{
textbox2.SelectAll();
}
And in designer
add:
this.textBox1.Click += new System.EventHandler(this.textBox1_Click);
under textbox1
and
this.textBox2.Click += new System.EventHandler(this.textBox2_Click);
under textbox2
Alternatively you can add event handlers in your code. It is useful when you create dynamic controls.

How to call an event handler from one control to the another control?

In Visual C# Form Application, When I Click on the button I want to add to the other controls(like listboxes,labels,textboxes) in same form.
How do I do this?
I have no idea what "to come to the other controls" might mean. But the event handlers in your Form derived class is the switchboard. Implement the button's Click event and have it do whatever you want done with any other controls. A trivial example:
private void button1_Click(object sender, EventArgs e) {
label1.Text = "You clicked the button!";
}
In the form designer, add an event handler to the button's Click event.
The form designer will give you a new method like this; add your code into this method:
private void button_Click(object sender, EventArgs e)
{
// Write some code that uses list boxes, labels, text boxes etc.
}
You question is somewhat unclear, but if you simply want to access other controls on the form, just go ahead and do so:
private void YourButton_Click(object sender, EventArgs e)
{
string someValue = yourTextBox.Text;
// do something with the value
}
If you want to add one event handler to many controls, you can do it.
Just go to properties of control you wish to subscribe, find appropriate event from list (ex: onClick) and choise your existed handler.
But this method will be sutable if events compotable.
Describe your task more detail.

C# TreeView SetFocus firing leave event twice

I have this simple code, where when the user leaves the TextBox control, TreeView gets focused:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.treeView1.Nodes.Add("A");
this.treeView1.Nodes[0].Nodes.Add("A.A");
this.treeView1.Nodes.Add("B");
this.treeView1.Nodes[0].Nodes.Add("B.A");
}
private void textBox1_Leave(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Leave..");
this.treeView1.Focus();
}
}
If we execute this code the Leave event is fired twice:
Leave..
Leave..
But if we set focus to other control, only one Leave event is fired.
Is that a problem of the TreeView? Do you know any workaround? Should we report this to Microsoft?
Thanks,
RG
this.treeView1.Focus();
Do not use the Focus() method in an event handler that's called because of a focusing event, like Leave. If you need to prevent a focus change then use the Validating event instead. Setting e.Cancel = true stops it.
But do note that this isn't very logical to do so for a TreeView, there isn't anything the user can do to alter the state of the control. You'll trap the user. Maybe that was the intention, do make sure the user can still close the window. If not then you might need the FormClosing event to force e.Cancel back to false.
Given that there is no code there to wire up the event I'm guessing you did it from the designer which means a line of code such as
textBox1.Leave += new EventHandler(textBox1_Leave);
will have been added to the Form1.designer.cs, check this file to ensure the line doesn't exist more than once as for each time this line is run you will get an event trigger, so if you run the line 3 times the Leave event will fire 3 times when you leave the textbox!
HTH
OneShot

Routing Key events to other control

Is there any standard way to route all Key events from the control A to other control B? I wish that the keyboard focus will still be on A however the event handler of A would trigger the all event handlers of B for the key events.
edit: Clarification: calling a specific event handler I wrote for B is not enough. I need to mimic the actual event. So for example I want that if a key is sent to a TextBox, it would be written to the TextBox. The solution given below does not do that (not to mention the fact that if new event handlers are added to B it completely fails).
I'm aware that WPF differentiates between logical focus and keyboard focus, but I need both focuses to remain on control A, but in a certain cases route its incoming event to other controls.
Couldn't you do something like this?
private void button1_Click(object sender, RoutedEventArgs e)
{
// Check if the event needs to be passed to button2's handler
if (conditionIsMet)
{
// Send the event to button2
button2.RaiseEvent(e);
}
else
{
// button1's "Click" code
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
// button2's "Click" code
}
Edit: Modified code to use the RaiseEvent() method to programmatically raise a specific event, rather than just calling the event handler for button2.

DataGridView and the CellEndEdit Event

I have a DataGridView, and would like to hook into the CellEndEdit event. I've been able to successfully hook into the CellContentClick event, but am having issues with CellEndEdit.
I added the following code to my Form1.cs file:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellCancelEventArgs e)
{
dataGridView1[0, 0].Value = "Changed";
}
With that code, nothing happens when I am done editing a cell. Is there anything else that I need to do to successfully hook into this event? I see that CellContentClick has a
this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick);
line of code in the Form1.Designer.cs file, but I tried to mimic this for CellEndEdit, and received a compile error
(No overload for 'dataGridView1_CellEndEdit' matches delegate
'System.Windows.Forms.DataGridViewCellEventHandler')
You could implement this yourself.
In your constructor you could have a HookEvents() method which wires up such events.
Or, within the form designer, click the gridview to select it, go to the properties window and click the yellow thunderbolt to find a list of events. Then, scroll down and find the CellEndEdit event and double click it - this will wire up the event for you.
To wire it up yourself, it may look like:
class A : Form
{
public A()
{
Initialize();
HookEvents();
}
private void HookEvents()
{
dataGridView1.CellEndEdit += dataGridView1_CellEndEdit;
}
}
I doubt very much that your solution would work.
It's not a matter of where you place the subscription, is how you do it.
Brandon, you are declaring an EventHandler, that is the function responsible of doing what you want to do in case of that event "dataGridView1_CellEndEdit" but you are not subscribing to the event. Also in your function you are passing the wrong parameters.
The easy solution is either subscribe from the designer window or by code doing this:
write "dataGridView1.CellEndEdit +=" and then press the TAB buton twice. That shoud create the code for subscription to the event and the correct delegate to handle it.

Categories