views:

399

answers:

1

I've got a small DataForm and I want to set the focus on the first TextBox. I'm using the Novermber 2009 Toolkit. I've named the TextBox and tried using .Focus() from the DataForm's loaded event. I see it get focus for one cursor 'blink' and then it's gone. I'm trying to work out if this is an artefact of the DataForm or something else. Does anyone know if I should be able to do this?

A: 

Try calling my custom focus setting function (FocusEx).

internal static class ControlExt 
{ 
    // Extension for Control 
    internal static bool FocusEx(this Control control) 
    { 
        if (control == null) 
                return false; 

        bool success = false; 
        if (control == FocusManager.GetFocusedElement()) 
                success = true; 
        else 
        { 
                // To get Focus() to work properly, call UpdateLayout() immediately before 
                control.UpdateLayout(); 
                success = control.Focus(); 
        } 

        ListBox listBox = control as ListBox; 
        if (listBox != null) 
        { 
                if (listBox.SelectedIndex < 0 && listBox.Items.Count > 0) 
                        listBox.SelectedIndex = 0; 
        } 

        return success; 
    } 
} 

That should work for you.

Jim McCurdy
Thanks for the suggestion. I've tried it but it didn't help: I get the same results. The TextBox has the focus briefly, then loses it. If I comment out the .Focus() or, using your code, the .FocusEx() statement, it doesn't get the focus at all, so I know they're working to start with. Something else must be stealing it but I don't know how to work out what it is.
serialhobbyist