Hunter Mitchell
Hunter Mitchell

Reputation: 7293

Getting focused textbox in C#?

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?

Upvotes: 0

Views: 413

Answers (3)

Steve
Steve

Reputation: 216323

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();
}

Upvotes: 1

Adi Lester
Adi Lester

Reputation: 25211

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.

Upvotes: 2

James Gaunt
James Gaunt

Reputation: 14783

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

Upvotes: 3

Related Questions