18 April 2011

Add service reference dynamically from user control

Steps:-

1. Create a New Website using Visual Studio 2008 or newer.
2. Create a usercontrol and Call it MyUserControl.
3. Create a function called AddScriptReferenceDynamically as 
    private void AddScriptReferenceDynamically()
    {
        ScriptManager scriptManger = ScriptManager.GetCurrent(this.Page);
    
    if (scriptManger != null) 
        
            ServiceReference serviceReference = new ServiceReference(); 
            serviceReference.Path="~/MyWebService.asmx";
   
         serviceReference.InlineScript = false;  
            scriptManger.Services.Add(serviceReference);    
        }
   
     else 
        
            throw new Exception("Script Manager Not Found"); 
        }
    } 

4. Override controls init event as 
    protected override void OnInit(EventArgs e)
    {
     
   AddScriptReference(); 
        base.OnInit(e); 
    } 

Thats it you done with it. Now just create a webpage in Your project and add a instance of control to your page.