0

I have 25 textboxes. I have one button that will paste information in a Selected textbox(The one that is focused). Here is the code i had used:

    foreach (Control z in this.Controls)
        {
            if (z is TextBox)
            {  
                ((TextBox)(z)).Paste();          
            }
        }

When i use this, all of the textboxes get pasted in. I only need the focused one. I am completely stumped. How do i fix this problem?

Hunter Mitchell
  • 7,063
  • 18
  • 69
  • 116
  • 4
    Make your button a ToolStripButton, it doesn't steal the focus when you click it. Now you can use the ActiveControl property. – Hans Passant Jun 23 '12 at 17:26
  • Further to the comment from @HansPassant this question has covered what you need http://stackoverflow.com/questions/435433/what-is-the-preferred-way-to-find-focused-control-in-winforms-app – David Hall Jun 23 '12 at 17:27

3 Answers3

3

How about this?

 foreach (Control z in this.Controls)
        {
            if (z is TextBox && z.Focused)
            {  
                ((TextBox)(z)).Paste();          
            }
        }

According to MSDN Control.Focused is true if the control has focus, otherwise false

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focused.aspx

James Gaunt
  • 14,631
  • 2
  • 39
  • 57
2

You can use LINQ to get the focused TextBox and paste.

TextBox focusedTextBox = this.Controls.OfType<TextBox>().FirstOrDefault(tb => tb.IsFocused);
if (focusedTextBox != null)
{
    focusedTextBox.Paste();
}

For WPF/Silverlight, the IsFocused property should be used. In case you're using winforms, you should use the Focused property.

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
1

You could try testing the Focused property of the controls collection

foreach (Control z in this.Controls) 
{ 
    if (z is TextBox && z.Focused) 
        ((TextBox)(z)).Paste();           
} 

However this could become more complicated if the TextBox are contained inside different GroupBoxes or other control containers.
In that case you need a recursive function

private void PasteInFocusedTextBox(ControlCollection ctrls)
{
    foreach (Control z in ctrls) 
    {
        if(z.Controls != null && z.Controls.Count > 1)
            PasteInFocusedTextBox(z.Controls);

        if (z is TextBox && z.Focused) 
           ((TextBox)(z)).Paste();           
    }
}

EDIT: Rereading your question I have a doubt. If you click a button to execute the paste operation, then the focus will be switched to that button and you can no more use the focused property

In this case you need to save in a global var the last textbox with focus before the click on the command button

private TextBox _txtLastFocused = null

private void txtCommon_Leave(object sender, EventArgs e)
{
    _txtLastFocused = (TextBox)sender;
}

private void cmdPasteButton_Click(object sender, EventArgs e)
{
   if(_txtLastFocused != null) _txtLastFocused.Paste();
}
Steve
  • 213,761
  • 22
  • 232
  • 286