简体   繁体   中英

Cannot Pass String to Page.SetFocus

Client wants after a save (post back) that the cursor returns to the last text box. I have it all setup but Page.SetFocus will not accept the variable _toFocus. But if I hard code it, it works flawlessly.

    protected void TextChangedCheckFail(object sender, EventArgs e)
    {
        TextBox someTxt = sender as TextBox;
        _toFocus = someTxt.ID.ToString();
        //_toFocus = "\"" + someTxt.ID.ToString() + "\"";  Does NOT work
        if (Page.IsPostBack)
        {
            lblTest.Text = _toFocus;  //This label always shows that _toFocus is accurate ID
            //sets focus to the proper control
            Page.SetFocus(_toFocus);  //Does not work
            Page.SetFocus(txtDate);   //Works perfectly

        }
        DidItFail();
    }

For the life of me I cannot figure out why you cannot pass a variable.

ANSWERING my own question to help others. Because Page.SetFocus requires you pass a CONTROL!

Page.SetFocus(someTxt); works perfect (someTxt was the TextBox i created out of sender).

As I was posting (after two hours of insanity) I figured out my problem.

My new code

protected void TextChangedCheckFail(object sender, EventArgs e)
{
    TextBox someTxt = sender as TextBox;
    if (Page.IsPostBack)
    {
        //sets focus to the proper control
        Page.SetFocus(someTxt);
    }
    DidItFail();
}

You can set focus by just calling focus on the textbox itself; TextBoxID.Focus();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM