Ankur
Ankur

Reputation: 1021

asp.net textbox focus problems

I am trying to set focus on textbox on page load in asp.net as follows

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
               // fillUnitType();
                //
                fillLastCode();
                txt_Grn_Date.Text = System.DateTime.Now.ToString("dd-MM-yyyy");
                setinitialrow_lvl();
 txt_Po_No.Focus();

            }
        }
        catch (Exception ex)
        {

            lblMessage.Text = ex.Message;
        }
    }

But the textbox is not getting focused. What is that I am missing. I have used update panel is it because of that.? Or my css is slightly faulty.

Upvotes: 0

Views: 9400

Answers (4)

Prabhakaran Parthipan
Prabhakaran Parthipan

Reputation: 4273

Try this code..

string jsCode= "<script language=javascript>document.getElementById('<%= TEXTBOX.ClientID%>').focus();</script>";   


ClientScript.RegisterClientScriptBlock(GetType(), "txtbox",jsCode, false);

Upvotes: 0

Sasidharan
Sasidharan

Reputation: 3740

I have tried this with updatepanel and textbox inside it.

CodeBehind

CodeBehind

.aspx

.aspx

output

Output

Upvotes: 1

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38683

try this in javascript

<script language=javascript>

function fnLoad(){
document.getElementById("<%= txt_Po_No.ClientID %>").focus();

}

</script>

call "fnLoad()" function on "onLoad" event of body..

You need to add this function in body tag : Like

<body onload="fnLoad()">........</body>

Update:

try another way

<script language=javascript>
    $(document).ready(function(){  document.getElementById("<%= txt_Po_No.ClientID %>").focus();}) 
  </script>

or

<script language=javascript>
        $(window).load(function(){  document.getElementById("<%= txt_Po_No.ClientID %>").focus();}) 
      </script>

Upvotes: 1

Sasidharan
Sasidharan

Reputation: 3740

Write following function in your codebehind and for every control call this function

private void Set_Focus(string controlname)
{
string strScript;

strScript = "<script language=javascript> document.all('" + controlname + "').focus() </script>";
RegisterStartupScript("focus", strScript);
}

Set

tapindex = 0
TextBox1.Focus();

or

 textBox1.Select();

or

 protected override void OnShown(EventArgs e)
    {
        textBox1.Focus();
        base.OnShown(e);
    }

or

setTimeout("myFocusFunction()", 500);

    function myFocusFunction(){
        $("#myTextBoxID").focus();
    }

Upvotes: 1

Related Questions