'Dynamically created keydown event does not work
I'm trying to make some often-used code more userfriendly.
I have a system that I use frequently in WinForms where the user needs to double-click a label to be able to edit the label.
Before, I always created the textbox and manually linked the KeyDown Event to the KeyDown EventHandler. But I wanted to make this easier by adding the eventhandler in the code.
However, when I do it this way, the KeyDown event isn't triggered.
Below This is the code to trigger the function that adds the KeyDown event to the TextBox
private void lbl_DoubleClick(object sender, EventArgs e)
{
// LINK THE LABEL
Label lbl = (Label)sender;
// SET THE LABEL AS THE SELECTEDLABEL
selectedLabel = lbl;
// OPEN THE EDIT TEXTBOX
editText();
}
private void editText()
{
// SETUP THE PARAMETERS OF THE EDIT TEXTBOX
txtEdit.Parent = this;
txtEdit.KeyDown -= txtEdit_KeyDown;
txtEdit.KeyDown += txtEdit_KeyDown;
// SOME OTHER CODE IS OMITTED FOR CLARITY
}
The above code links the KeyDown to the Event Handler. At some point I found that I needed to relink the Event Handler every time, however, I'm not sure anymore why that was. I can't find the original post anymore.
Below is the Event Handler:
private void txtEdit_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Escape:
// HIDE THE EDIT TEXTBOX
txtEdit.Visible = false;
// CLEAR THE SELECTED LABEL
selectedLabel = null;
break;
case Keys.Enter:
break;
}
}
When I run the code, the Textbox gets created and the contents of the label are copied in the textbox. However when I hit any button inside of the
txtEdit textbox, the Key Down Event Handler is not being fired.
I have checked that in the Designer there is no Event Handler specified which might interfere with my new one:
//
// txtEdit
//
this.txtEdit.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtEdit.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtEdit.ForeColor = System.Drawing.Color.Black;
this.txtEdit.Location = new System.Drawing.Point(1607, 225);
this.txtEdit.Multiline = true;
this.txtEdit.Name = "txtEdit";
this.txtEdit.Size = new System.Drawing.Size(100, 35);
this.txtEdit.TabIndex = 22;
this.txtEdit.Text = "Edit";
this.txtEdit.Visible = false;
So I have no idea why this isn't working. Anybody has an idea?
Thanks
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
