Generally where only one option lefts to Choose from a list of records we use Dropdownlist Control. Let’s talk about a Country dropdownlist. What you need to do is need to fetch records from Database. In second step need to bind that data to the data-source of ASP.NET dropdownlist. The same I did in the below example.
The logic here I implement is very simple. Using ExecuteReader I am executing my command object against a DataReader. Then with the conditional check DataReader.read method I am running a while loop. Inside this loop adding new listitems with key & value pair from DataReader.
Compare to DataSet DataReader executes faster. DataReader is like a pointer. While DataSet is Connection less architecture.
dropdown
<asp:DropDownList ID="ddlOrgType" runat="server" TabIndex="3" ToolTip="Select your Organization Type" Width="244px" AutoPostBack="True"></asp:DropDownList>
Connection String I Used
Dim connObj As New SqlConnection(ConfigurationManager.AppSettings.Get("connString").ToString())
in web.config:
<appSettings> <add key="connString" value="Data Source=localhost; uid=sa; pwd=tiger; database=TRAINNINGMANAGER;"/> </appSettings>
SelectedIndexChanged event of dropdown
Protected Sub ddlOrgType_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlOrgType.SelectedIndexChanged ddlDivision.Items.Clear() 'Fill up ddlDivision dropdownlist from DivisionTab Dim commDivision As New SqlCommand("SELECT * FROM DivisionTab WHERE divisionStatus='1' and fkTypeOrgID=" & ddlOrgType.SelectedValue.ToString, connObj) Try connObj.Open() Dim Objdr As SqlDataReader = commDivision.ExecuteReader ddlDivision.Items.Add(New ListItem("Please Select...", 0)) While Objdr.Read ddlDivision.Items.Add(New ListItem(Objdr(1), Objdr(0))) End While Catch ex As Exception Response.Write(ex.ToString()) Finally connObj.Close() End Try End Sub