Question

What I want to do is to validate the given input by the user and then set a focus on the invalid input in text box.

My save button function is given below.

protected void btnSave_OnClick(object sender, EventArgs e)
{
    try
    {          
        if (ValidateForm())
        {
            Users objUser = new Users();
            objUser.Username = this.txtUsername.Text;
            objUser.Password = this.txtPassword.Text;
            objUser.Add();

            this.labelMessage.Text = "User has been saved successfully";
        }
    }
    catch (Exception ex)
    {
        Monitoring.WriteException(ex);
    }
}

Validation function to validate the given input is not null or empty.

private bool ValidateForm()
{
    bool isvalidate = true;

    try
    {
        string username = this.txtUsername.Text;
        string password = this.txtPassword.Text;

        if (username == "" || username == string.Empty)
        {
            this.labelMessage.Text = "Please enter username";
            this.txtUsername.Focus();
            isvalidate = false;
        }
        else if (password == "" || password == string.Empty)
        {
            this.labelMessage.Text = "Please enter password";
            this.txtPassword.Focus();
            isvalidate = false;
        }
    }
    catch (Exception ex)
    {
        Monitoring.WriteException(ex);
    }
    return isvalidate;
}

The problem is the I am unable to set focus to any textbox after validation. Anyone know where I am wrong? Or there is any other better way? I have searched a lot but most of them setting the focus on Page load (Post back). I want to do it from code behind.

Était-ce utile?

La solution

Try the following Code. Use this code in your code behind. And pass your textbox id to SetFocus function. It will surely solve your problem.

Replace this code

this.txtUsername.Focus();

With this code

ScriptManager.GetCurrent(this.Page).SetFocus(this.txtUsername);

Given below is a tested code.

private bool ValidateForm()
{
    bool isvalidate = true;

    try
    {
        string username = this.txtUsername.Text;
        string password = this.txtPassword.Text;

        if (username == "" || username == string.Empty)
        {
            this.labelMessage.Text = "Please enter username";
            ScriptManager.GetCurrent(this.Page).SetFocus(this.txtUsername);
            isvalidate = false;
        }
        else if (password == "" || password == string.Empty)
        {
            this.labelMessage.Text = "Please enter password";
            ScriptManager.GetCurrent(this.Page).SetFocus(this.txtPassword);
            isvalidate = false;
        }
    }
    catch (Exception ex)
    {
        Monitoring.WriteException(ex);
    }
    return isvalidate;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top