开发者

How to set focus to an object(textbox) in main form from another form (C#)

开发者 https://www.devze.com 2023-02-19 21:17 出处:网络
I tried everything I know. The trouble must be that my textbox is in a groupbox. I have a Mainform from which I move to another form. When I return to Mainform, I want a particular object to be focuse

I tried everything I know. The trouble must be that my textbox is in a groupbox. I have a Mainform from which I move to another form. When I return to Mainform, I want a particular object to be focused. How is this done? Here's my code in my Mainform.

    private void button1_Click(object sender, EventArgs e)
    {
         Form1 frm = new Form1();
         frm.ShowDialog();
    }

now this is how i return back to my Mainform from Form1.

    private void button3_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.OK;
    }

I have textBox1 in Mainform. How to set focus to textBox1 when quitting Form1 and entering Mainform. I tried textBox1.Focus(); and this.ActiveControl = this.textBox1; under Mainform Load, Show, Activated and Enter events. Still didn't work. I tried creating a public m开发者_开发技巧ethod and call it under the exit button of Form1. Like this.

In Mainform,

    public void textBox1Focus()
    {
        textBox1.Focus();
    }

And then in Form1,

    private void button3_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.OK;
        Mainform frm = new Mainform();
        frm.textBox1Focus();
    }

Which still didn't work. My textBox1 is in a groupbox. Could that be the reason?

Thanks.


I don't understand how the code that you've shown even compiles. You're calling textBox1Focus() from inside a method that's defined in the Form1 class, which as best I can understand, doesn't include a definition for textBox1Focus. That method is only defined in the Mainform class.

And no, the text box being placed in a group box is not preventing it from getting the focus. There's something else wrong with your code. It's hard to tell; I feel like I'm looking at a sunset through Venetian blinds, rather than through a large picture window.

Anyway, I suspect there's a simpler solution. Just set the focus to the textbox control at the end of the button1_Click method. The ShowDialog method is a blocking call, which means execution won't continue until after the user closes the second form. When that happens, execution will continue with the next line of code, which will set the focus to the textbox control.

Try changing your code to the following:

private void button1_Click(object sender, EventArgs e)
{
     Form1 frm = new Form1();
     frm.ShowDialog();
     this.textBox1.Select();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消