Home arrow GIS Data & Resources arrow Scripts and Code arrow C# Code arrow C# Populate DropDownList with SOAP Web Service
C# Populate DropDownList with SOAP Web Service PDF Print E-mail

Written by Steve Gourley,

Have you ever wanted to populate a drop down list using a different method than a SQLDataSource, reading a file, or the results of a query and iteratively populating the ListItems? SQLDataSources are very nice if your data is stored in a  database, which isn't always the case.


I wanted a cleaner way to do this and thought using a SOAP web service would be that way. This would keep the clutter code in the web service and my project's code clean and easily readable. Also, if many applications were using the same web service, modifying the list would be very easy and fast. It had to be possible to set one web service call to a property of the Drop Down List and it would just work.  


Well, I ran into some problems, but having the flexibility to modify the soap string that the web service returned was quite helpful.

The first thing I tried was changing the return type of the web service to be a System.Web.UI.DataSources.ListItemCollection. Then I realized that the DropDownList property ListItems is read only.  
Next, I tried populating the DropDownList.Items.AddRange() which takes a ListItem[]. What I found out was that my SOAP service was returning a ListItems[] but it was appending the web reference name before so there was a type mismatch. Couldn't cast from webreference.ListItem[] to System.Web.UI.DataSources.ListItem[]. Frustrating.  


 Finally, I tried changing the return type of the web service to object and setting the DropDownList.DataSource = webservice.call(); DropDownList.DataBind(); and it worked!

 Another caveat though. You can't populate the value field of the DropDownList. This was another requirement for me so I looked into another way. I thought, how does the SQLDataSource do it?  The answer is DataTables.

Build a DataTable (ensure you give the table a name or it can't be serialized) and add a DataColumn for Text and for Value. Then populate your table with new DataRows. Set the DataTextField and DataValueField to your DataColumn names and call a DataBind and it works.

/*Web Service Snippet */

DataTable dt= new DataTable("tablename");
         
dt.Columns.Add("text", Type.GetType("System.String"));
dt.Columns.Add("value", Type.GetType("System.String"));

DataRow row = dt.NewRow();
row["text"] = "Steve";
row["value"] = "123212";

dt.Rows.Add(row);

return dt; 

/* Populate DDL */ 

DDL.DataTextField = "text";
DDL.DataValueField = "value";
DDL.DataSource = webService.Call();
DDL.DataBind();

 


Users' Comments  
 

No comment posted

Add your comment

21, Feb. 2008
Last Updated ( 03, Jun. 2008 )
 
< Prev   Next >

AGRC Contacts | UGIC Contacts

feed image feed image

Utah GIS Portal © 2009 AGRC

Optimized for