Wednesday, December 22, 2004

Setting focus for Web Form Control

About Example :

aspx page have two textbox web form controls [txtUserName and txtPassword], a button web form control [btnLogin] and a hidden web form control [hdnControlName], Example is to check whether any value is entered in the textboxes on button click. If not, it displays an alert message and set focus on the control.





/* This is the code for setting focus for Web Form Control */

/****************************************************

Registering a startup script to set focus on web form control

Code to be placed in code behind file
****************************************************/

public void SetFocus(string s1)

{

string s = "<"+"script "+"language"+"="+"'javascript'>document.getElementById('"+s1+ "').focus() <"+"/"+"script"+">";

if(!this.IsStartupScriptRegistered("focus"))

Page.RegisterStartupScript("focus", s);

}



/* Script to check which control to be set focus */


/*******************************************************

javascript function to check whether value is entered in the textboxes or not

Code to be placed in aspx page inside script tag

*******************************************************/

function fnLogin()

{

strUserName = document.frmLogin.txtUserName.value

strPassword = document.frmLogin.txtPassword.value

if(strUserName == "")

{

document.frmLogin.hdnControlName.value = "txtUserName";

alert("Please enter User Name")

}

else if(strPassword == "")

{

document.frmLogin.hdnControlName.value = "txtPassword";

alert("Please enter Password")

}

}





/* Register the script on Page_Load */


/****************************************************************************
register the javascript for validation [above code] on button click inside page load

Code to be placed in code behind file

****************************************************************************/

private void Page_Load(object sender, System.EventArgs e)

{

btnLogin.Attributes.Add("OnClick","fnLogin()");

}


/* Function to execute on button click */

/*****************************************************

Code to be placed in code behind file

*****************************************************/
private void btnLogin_Click(object sender, System.EventArgs e)

{

/* Check whether the hidden control value is null or not */

/* If not null then call SetFocus function with hidden control value as parameter */

}








No comments: