Dear group,
I have a very strange behaviour:
In a loop there are several TextBoxes initialized:
[Pseudo-Code]
TextBox objTextBox = null; // one declaration
for-loop // multiple initialisations
objTextBox = new TextBox();
objTextBox.ReadOnly = true;
objTextBox.Name = "TxtBox" + i.ToString();
objTextBox.Enter += new System.EventHandler(this.objTextBox_Enter);
.
.
.
/for-loop
.
.
.
private void objTextBox_Enter(object sender, System.EventArgs e)
{
((TextBox)sender).SelectAll();}
[/Pseudo-Code]
When setting a breakpoint in objTextBox_Enter(), the programm performs
((TextBox)sender).SelectAll(), but the TextBox.Text is not selected (the
cursor is still in the TextBox).
When performing a MessageBox.Show() after ((TextBox)sender).SelectAll()
as shown below, my TextBox.Text is selected.
[Pseudo-Code]
private void objTextBox_Enter(object sender, System.EventArgs e)
{
((TextBox)sender).SelectAll();
MessageBox.Show("DEBUG");}
[/Pseudo-Code]
Could someone please give me a hint, what the problem is (focus-problem
etc.)?
I wonder if it's a good idea to declare one TextBox-Variable and
initialise multiples. The TextBoxes are distinguished through TextBox.Name.
For your information: This is code from a former developer.
Hope you can help me.
Regards,
Werner
I Assume you're trying to replicate the behaviour that when the
textbox gets focus and selects all.
Well, I had a play, I tried adding all the event handlers (well not
all, the ones I thought might be culprits) and printed to the console
to see what order they fire in.
Next I tried creating a class derived from textbox and overriding
various control OnSomething methods and not calling base.
I stopped short of overriding wndproc as you get spammed but I'm
guessing you'll see the textbox getting focus and immediately losing
it as the msgbox pops up.
So my solution was to add a flag to the class
private bool _test = false;
Setting it to true on the enter event
Console.WriteLine("Enter");
_test = true;
and then checking in mouseup
Console.WriteLine("Mouse up");
if(_test)
{
_test = false;
((TextBox)sender).SelectAll();
}
This seems to achieve what you were looking for.