0

I have in my project 5 text boxes. Every TextBox should accept only digits. For that I created a function which takes not prepared text and returns the proper one. Now I'm wondering if there is any simpler way to perform this action on every TextBox, on every TextChanged event without repeating almost same code?

private void TextGoldPack_TextChanged(object sender, EventArgs e)
{
    (sender as TextBox).Text = Only_digits((sender as TextBox).Text);
}

private void TextGoldTake_TextChanged(object sender, EventArgs e)
{
    //repeat here and on every _TextChanged event
}
Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
sobczi
  • 121
  • 7
  • Possible duplicate of [How call the Text\_Changed Event for multiple text box controls on a form in C# winforms](https://stackoverflow.com/questions/28501520/how-call-the-text-changed-event-for-multiple-text-box-controls-on-a-form-in-c-sh) – Eliahu Aaron Jun 25 '19 at 19:46

2 Answers2

3

If I'm understanding you correctly, just because it's named TextGoldTake_TextChanged, doesn't mean that's the only textbox that can use that code. On the events tab, you can set the TextChanged function for all you textboxes to lead to that function. If it helps, rename it something that doesn't sound textbox-specific such as TextChanged.

enter image description here

William V.
  • 343
  • 1
  • 13
  • Wow, now i feel kinda stupid. The problem was on my way of thinking about pre-created functions. Never thought about that they are actually simply functions which i can use whenever i want. – sobczi Jun 25 '19 at 19:03
1

Change all the TextBoxes to refer this method upon TextChanged. Use the sender property to get the actual caller TextBox.