Implement Country And Province/State Dropdown Lists in ASP.NET
In my project, the countries and prov/states are not stored in the database. I have some functions in a class.
'to get the Country list
Public Shared Function GetCountryList() As ArrayList
Dim alCountry As New ArrayList
alCountry.Add(New ListItem("", "-1"))
alCountry.Add(New ListItem("United States", "181"))
alCountry.Add(New ListItem("Canada", "32"))
alCountry.Add(New ListItem("Afghanistan", "1"))
alCountry.Add(New ListItem("Albania", "2"))
alCountry.Add(New ListItem("Algeria", "3"))
… …
Return alCountry
End Function
'to get the Prov/State list
Public Shared Function GetProvStateList(ByVal intCountry As Integer) As ArrayList
Dim alProvState As New ArrayList
alProvState.Add(New ListItem("", "-1"))
Select Case intCountry
Case 181
'United State
alProvState.Add(New ListItem("Alabama", "AL"))
alProvState.Add(New ListItem("Alaska", "AK"))
… …
End Select
Return alProvState
End Function
In Page_Load()
… …
ddlCountry.DataValueField = "Value"
ddlCountry.DataTextField = "Text"
ddlCountry.DataSource = MyClassName.GetCountryList()
ddlCountry.DataBind()
… …
In Page_PreRender()
'Bind data for ddlProvState here rather than the page_load,
'because the data source of ddlProvState is affected by ddlCountry.SelectedValue
ddlProvState.DataValueField = "Value"
ddlProvState.DataTextField = "Text"
ddlProvState.DataSource = MyClassName.GetProvStateList(ddlCountry.SelectedValue().ToString)
ddlProvState.DataBind()
In the case of further validation is needed to check the consistency between the values of country and prov/state, Page_PreRender() is a good place to handle it.