I am making a C# Windows Form project in Visual Studio 2019. I currently have 40 textboxes that users have to fill in. These textboxes are quite small, which is why at the top of the program I created a large label. I was wondering if it's possible in C# to display the text from the active textbox that the user is filling in within this label box. I'm not sure if this piece of information would have any baring on this process, but once the user fills in the correct information in the current said textbox, it automatically disables it and moves on to the next one.
So for an example:
Whenever the user enters anything in any of those textboxes, the active textbox text displays at the top (in the label).
In your form's constructor, add event handlers for the TextChanged
and Enter
events of all your TextBoxes. It should look something like this:
public Form1()
{
InitializeComponent();
foreach (var textBox in this.Controls.OfType<TextBox>())
{
textBox.TextChanged += TextBoxes_TextChanged;
textBox.Enter += TextBoxes_TextChanged;
}
}
Note that this.Controls.OfType<TextBox>()
will only work if the TextBoxes are placed directly on the form. If they're placed in another container (e.g., GroupBox or Panel), you may use the following instead:
theOtherContainer.Controls.OfType<TextBox>()
Then, you can change the Label's text using the following event handler:
private void TextBoxes_TextChanged(object sender, EventArgs e)
{
var textBox = (TextBox)sender;
label1.Text = textBox.Text;
}
You could also add event handlers for the Leave
event in order to clear the text when the cursor leaves a certain TextBox. To do that, just add the following line in the foreach
loop above:
textBox.Leave += (o, e) => label1.Text = string.Empty;