I have over 160 textboxes, each corresponds to the value inside registers in a chip. I want to write the values typed into the textboxes to the corresponding register each time enter is pressed from that particular textbox. Since there are lot of textboxes keydown event is not possible to every textboxes. What should i do here?. How can i get the name of the textbox the user types the data and then pressed the enter , so that i can take the value from that particular box and copy it.
Asked
Active
Viewed 341 times
0
-
2Why is `KeyDown` not possible? Make one event handler, hook them all up and identify which is the `sender` either via a `dictionary` or by setting the `Tag` property – Charlieface Jan 18 '21 at 16:02
-
1Thank you so much. This helped to figure out the problem – Faris Kamal Kakkengal Jan 18 '21 at 18:11
-
I completed that step but now confronted with another problem. Some textboex which is inside anothe panel are not showing up in event handler. What can i do here? – Faris Kamal Kakkengal Jan 19 '21 at 09:40
1 Answers
2
Surely you can hook into the keypress event in the form constructor.
public Form1()
{
InitializeComponent();
foreach (Control control in this.Controls)
if (control is TextBox)
((TextBox)control).KeyPress += new KeyPressEventHandler(TextBox_Keypress);
}
private void TextBox_Keypress(object sender, KeyPressEventArgs e)
{
var textbox = sender as TextBox;
MessageBox.Show(textbox.Name + "has typed a key");
}
Digging Deeper into Children
If you need to fetch textboxes within children PsychoCoders answer can help you.
public IEnumerable<Control> GetAll(Control control, Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAll(ctrl, type))
.Concat(controls)
.Where(c => c.GetType() == type);
}
and change your foreach
like so;
foreach (Control control in GetAll(this, typeof(TextBox)))
{
...
}

clamchoda
- 4,411
- 2
- 36
- 74
-
1Thank you so much, this helped me a lot. So grateful for the quick response – Faris Kamal Kakkengal Jan 18 '21 at 18:10
-
Hi, i have encountered an another problem. My textboxes are scattered in different panels and groupboxes and it seems like control is not going inside that. When the textbox is kept outside all the panel or groupbox it is working. What can i do here. Any help will be highly appreciable – Faris Kamal Kakkengal Jan 19 '21 at 09:26