Thursday, February 16, 2012

Calling Javscript from code-behind

We can call javascript alert messages from code-behind(on say button_click event etc..) as below:

//Display success message (several ways) shown here
//Method 1
string st = "script language='javascript'" + "window.alert('CustomerId' :" + CustId + " deleted successfully)" + "/script";
Page.ClientScript.RegisterClientScriptBlock(GetType(),"del_successMessage", st, false);


//Method 2
//Here the Javascript function is written normally in the script tag in the Head section of the HTML page.
Page.ClientScript.RegisterStartupScript(GetType(),"Javascript", "javascript: fnShowSuccessMessage();",true);


//Both the above methods do not work if we use Update Panel as a container..see solution that works below.

System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"script language='javascript'");
sb.Append(@"alert('CustomerId :" + CustId + " deleted successfully');");
sb.Append(@"/script");
ScriptManager.RegisterStartupScript(btnDelete, GetType(), "MyJavaScript", sb.ToString(), false);
I had to remove tags on the script tag in order to post it.

To Check if the dropdownlist has a given value before selecting it

To Check if the dropdownlist has a given value before selecting it:

ListItem li = ddlItems.Items.FindByValue(MyNr.ToString());
if (li != null) //Item Found in dropdown..so select it and display details
{
//Value was found
}
else
{ //not found }