I am little confused for creating website menu & sub menus which is completely dynamic & made from database. For Menus I used Listview Control which is fine now all menus have submenus(child menu) as well which is based on menus. Now I don't understand how to do it. I guess using nested ListView would be good for this but I need an hint how to bind nested listview?
This is my main Listview
<asp:ListView ID="mainMenu" runat="server">
<ItemTemplate>
<li><asp:HyperLink ID="mainLinks" runat="server" NavigateUrl='<%# Eval("name", "~/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink>
<ul class="super-child">
<asp:ListView ID="childMenu" runat="server">
<ItemTemplate>
<li><asp:HyperLink ID="cat3" runat="server" NavigateUrl='<%# Eval("category") & Eval("name", "/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink></li>
</ItemTemplate>
</asp:ListView>
</ul>
</li>
</ItemTemplate>
</asp:ListView>
Private Sub bigMenu()
Dim constr As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand()
cmd.CommandText = "SELECT * FROM mainMenu WHERE status = 'active' order by CAST(position as SIGNED INTEGER) asc"
cmd.Connection = con
Using sda As New MySqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
mainMenu.DataSource = dt
mainMenu.DataBind()
End Using
End Using
End Using
End Sub
You need to use ListView ItemDataBound to bind your nested listview. ItemDatBound will get rows value for you. See the below code I done for you
<asp:ListView ID="mainMenu" runat="server" DataKeyNames="enter column name you want">
<ItemTemplate>
<li><asp:HyperLink ID="mainLinks" runat="server" NavigateUrl='<%# Eval("name", "~/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink>
<ul class="super-child">
<asp:ListView ID="childMenu" runat="server">
<ItemTemplate>
<li><asp:HyperLink ID="cat3" runat="server" NavigateUrl='<%# Eval("category") & Eval("name", "/{0}") %>' Text='<%# Eval("name") %>'></asp:HyperLink></li>
</ItemTemplate>
</asp:ListView>
</ul>
</li>
</ItemTemplate>
</asp:ListView>
Protected Sub onItemDataBound(sender As Object, e As ListViewItemEventArgs)
If e.Item.ItemType = ListViewItemType.DataItem Then
Dim itm As ListViewDataItem = CType(e.Item, ListViewDataItem)
Dim name As String = mainMenu.DataKeys(itm.DataItemIndex)("enter your datakeyname")
Dim childMenu As ListView = TryCast(e.Item.FindControl("childMenu"), ListView)
Dim constr As String = ConfigurationManager.ConnectionStrings("conio").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand()
cmd.CommandText = "SELECT * FROM tablename WHERE column = '" + name + "'"
cmd.Connection = con
Using sda As New MySqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
childMenu.DataSource = dt
childMenu.DataBind()
End Using
End Using
End Using
End If
End Sub
Related
I am trying to fill a text box with an ID of O1IDText when the selected value of a drop down list is changed. I get an error "Object reference not set to an instance of an object".
Here is my code in ASP of the drop down list:
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" AutoPostBack="true" runat="server" DataSourceID="SqlDataSource2" AppendDataBoundItems="true" OnDataBinding="DropDownlist1_DataBinding1" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" DataTextField="FullName" DataValueField="FullName" SelectedValue='<%# Bind("Official1") %>'>
</asp:DropDownList>
</EditItemTemplate>
Below is the code of my Textbox wihtin ASP:
<EditItemTemplate>
<asp:TextBox ID="O1IDText" runat="server" Text='<%# Bind("O1ID") %>'></asp:TextBox>
</EditItemTemplate>
And Finally my code behind in VB:
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim ddList As DropDownList = CType(sender, DropDownList)
RemoveHandler ddList.DataBinding, AddressOf DropDownlist1_DataBinding1
Dim O1IDText As TextBox = TryCast(FindControl("O1IDText"), TextBox)
Dim cmd As SqlCommand = con.CreateCommand()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Select ID from Official where [First Name] + ' ' + [Last Name]+ ' ' +[Email]+ ' ' +[Phone] = '" + ddList.SelectedValue + "'"
Dim dr As SqlDataReader
Try
con.Open()
dr = cmd.ExecuteReader()
dr.Read()
O1IDText.Text = dr("ID").ToString
Catch ex As Exception
con.Close()
End Try
The exception "Object reference not set to an instance of an object" happens during O1IDText.Text = dr("ID").ToString.
Assuming that the DropDownList and the TextBox are both in the same row or item, you can get the TextBox this way:
Dim O1DText As TextBox = CType(ddList.NamingContainer.FindControl("O1DText"), TextBox)
In a detailsview I have a drop down list whose selection determines the list in a second Drop down list. When the web page loads all my "Get Data" Functions load the various Drop down boxes. After I make a selection in the first of the two related drop down boxes I call an "index changed" function that takes the value of the first drop down box, as a variable, and puts it into a SQL statement. This SQL statement runs correctly inside SQL. However, the second drop down doesn't reload with the new data the values in the second drop down remain the same. Here is the pertinent code:
` <asp:TemplateField HeaderText="Planting Hatchery">
<ItemTemplate>
<asp:Label ID="lblPlantHatch" runat="server" Text='<%# Eval ("HatcheryCodePlant")%>' Visible = "true"></asp:Label>
</ItemTemplate>
<insertItemTemplate>
<asp:DropDownList ID="ddPlantingHatchery" runat="server" DataSource='<%# GetPlantingHatchery()%>'DataTextField="HatcheryNamePlant" DataValueField="HatcheryCodePlant" width= "150" AppendDataBoundItems="true" AutoPostBack="true"
OnSelectedIndexChanged="ddPlantingHatchery_indexchanged">
<asp:ListItem Text="Select" Value="" />
</asp:DropDownList>
</insertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Water Body Name">
<ItemTemplate>
<asp:Label ID="lblStreamName" runat="server" Text='<%# Eval("CatalogNo")%>' Visible = "true"></asp:Label>
</ItemTemplate>
<insertItemTemplate>
<asp:DropDownList ID="ddCatalogName" runat="server" DataSource='<%# GetCatalogNames()%>'
DataTextField="StreamName" DataValueField="CatalogNo" AppendDataBoundItems="true" >
<asp:ListItem Text="Select" Value="" />
</asp:DropDownList>
<asp:ObjectDataSource ID="dsWaterBody" runat="server" TypeName="StreamName"
<SelectMethod="GetCatalogNames">
<SelectParameters>
<asp:ControlParameter Name="HatcheryCodePlant" Type="string" ControlID="ddPlantingHatchery" PropertyName="Selectedvalue"/>
</SelectParameters>
</asp:ObjectDataSource>
</insertItemTemplate>`
This is the Code Behind:`
Public Function GetPlantingHatchery() As DataSet
Dim myConnection As New SqlConnection(ConnectionString)
Dim ad As New SqlDataAdapter("SELECT HatcheryNamePlant, HatcheryCodePlant FROM HatcheryPlant Order by HatcheryNamePlant", myConnection)
Dim ds As New DataSet()
ad.Fill(ds, "HatcheryPlant")
Return ds
End Function
Public Function GetCatalogNames() As DataSet
Dim myConnection As New SqlConnection(ConnectionString)
Dim ad As New SqlDataAdapter("SELECT StreamName, CatalogNo, HatcheryNamePlant, HatcheryCodePlant, LLID FROM vwStockingWatersByHatchery Order By StreamName", myConnection)
Dim dsWaterBody As New DataSet()
ad.Fill(dsWaterBody, "Catalog")
Return dsWaterBody
End Function
Public Function ddPlantingHatchery_indexchanged(sender As Object, e As EventArgs)
Try
Dim ddCatNum As DropDownList = TryCast(dvSMasterCurrentYear.FindControl("ddCatalogName"), DropDownList)
'ddCatNum.SelectedValue = TryCast(dvSMasterCurrentYear.FindControl("ddPlantingHatchery"), DropDownList).SelectedValue
MySelectedValue = TryCast(dvSMasterCurrentYear.FindControl("ddPlantingHatchery"), DropDownList).SelectedValue
Dim myConnection As New SqlConnection(ConnectionString)
Dim ad As New SqlDataAdapter("SELECT StreamName, CatalogNo, HatcheryNamePlant, HatcheryCodePlant, LLID FROM vwStockingWatersByHatchery where HatcheryCodePlant = '" + MySelectedValue + "' Order By StreamName", myConnection)
Dim dsWaterBody As New DataSet()
ad.Fill(dsWaterBody, "Catalog")
Return dsWaterBody
Catch ex As Exception
End Try`
What do I need to do to load the second Drop down list with the new data?
I have a GridView as below:
<asp:GridView ID="gvChain" runat="server" Font-Size="Small" CellPadding="3" CellSpacing="1" GridLines="None"
AutoGenerateColumns="False">
<HeaderStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="Department" ControlStyle-Width="175px">
<EditItemTemplate>
<asp:Label ID="lblDepartment" runat="server" Text='<%# Bind("Department") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDepartment" runat="server" Text='<%# Bind("Department") %>'></asp:Label>
</ItemTemplate>
<ControlStyle Width="175px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Manager Level 1" ControlStyle-Width="175px">
<ItemTemplate>
<asp:Label ID="lblManager1" runat="server" Text=""></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="cbManager1" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ControlStyle Width="175px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Manager Level 2" ControlStyle-Width="175px">
<ItemTemplate>
<asp:Label ID="lblManager2" runat="server" Text=""></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="cbManager2" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ControlStyle Width="175px" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" CommandName="Edit" runat="server" Text="Edit" CssClass="buttonStyle" CausesValidation="false"/>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnSave" CommandName="Update" runat="server" Text="Save" CssClass="buttonStyle" CausesValidation="false"/>
<asp:LinkButton ID="btnCancel" CommandName="Cancel" runat="server" Text="Cancel" CssClass="buttonStyle" CausesValidation="false" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnDelete" CommandName="Delete" runat="server" Text="Delete" CssClass="buttonStyle" CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The BoundField is populated in the Page_Load event as below:
Dim dHandler As DepartmentHandler = New DepartmentHandler
Dim depts As New List(Of Department)
depts = dHandler.GetDepartmentList
gvChain.DataSource = depts.
If Not Page.IsPostBack Then
gvChain.DataBind()
End If
Populating of the TemplateFields is then done in the RowDataBound event as below:
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowState = DataControlRowState.Edit Then
Dim cbManager1 As DropDownList = TryCast(e.Row.FindControl("cbManager1"), DropDownList)
Dim cbManager2 As DropDownList = TryCast(e.Row.FindControl("cbManager2"), DropDownList)
Dim eHandler As EmployeeHandler = New EmployeeHandler
' Get the list of managers
Dim mgrs As New List(Of Manager)
mgrs = eHandler.GetManagerList
cbManager1.DataSource = mgrs
cbManager2.DataSource = mgrs
cbManager1.DataValueField = "Name"
cbManager1.DataTextField = "Name"
cbManager2.DataValueField = "Name"
cbManager2.DataValueField = "Name"
cbManager1.DataBind()
cbManager2.DataBind()
' Get the department name from the label in cell 0
Dim lbl As Label = e.Row.Cells(0).FindControl("lblDepartment")
Dim dept As Department = New Department
dept.Department = lbl.Text
' Pass the department name to the getManager1/2 functions to return the correct manager for that department
Dim mgr1 As Manager = eHandler.getManager1(dept)
Dim mgr2 As Manager = eHandler.getManager2(dept)
' Upper case the manager name to search the DDLs for item
Dim mgr1Name As String = mgr1.Name.ToUpper()
Dim mgr2Name As String = mgr2.Name.ToUpper()
' Find the manager in the DDL and select
cbManager1.SelectedValue = mgr1Name
cbManager2.SelectedValue = mgr2Name
Else
' If GV isnt in edit mode then populate labels in itemtemplate with manager 1 and 2 values
Dim lblManager1 As Label = DirectCast(e.Row.FindControl("lblManager1"), Label)
Dim lblManager2 As Label = DirectCast(e.Row.FindControl("lblManager2"), Label)
Dim eHandler As EmployeeHandler = New EmployeeHandler
Dim lbl As Label = e.Row.Cells(0).FindControl("lblDepartment")
Dim dept As Department = New Department
dept.Department = lbl.Text
Dim mgr1 As Manager = eHandler.getManager1(dept)
Dim mgr2 As Manager = eHandler.getManager2(dept)
lblManager1.Text = mgr1.Name
lblManager2.Text = mgr2.Name
End If
End If
I then have the below in the RowEditing event
gvChain.EditIndex = e.NewEditIndex
gvChain.DataBind()
When there is only 1 record displayed in the GridView, I click the edit button and the GridView goes into Edit mode I am able to update that record using the RowUpdating event and this works fine. However, if I add another record to the GridView, clicking on the edit button of that record gives a NullReference exception. If I then add another record, that 3rd record will go into edit mode. A 4th record will again fail with a NullReference exception and so on.
When debugging, it seems that on rows indexes 1,3,5 etc. the GridView doesn't go into edit mode however on row indexes 0, 2, 4 etc. the GridView will switch to edit mode.
This seems really strange behaviour. Any ideas what may be causing the GridView not to go into Edit mode on these rows?
A row's state can be one or a combination of the DataControlRowState values, so use bitwise operations to determine whether the state of the row includes a DataControlRowState value.
here
RowState contains more than one value (Alternate | Edit if you check RowState property during edit mode) using bit-logic.
Try
If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
I got round this by amending the getDepartmentList function to return the Manager1 and Manager 2 fields then databinding them in the same was as I had bound 'Department'.
I then amended the RowDataBound event to the following:
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowState And DataControlRowState.Edit Then
Dim cbManager1 As DropDownList = TryCast(e.Row.FindControl("cbManager1"), DropDownList)
Dim cbManager2 As DropDownList = TryCast(e.Row.FindControl("cbManager2"), DropDownList)
Dim eHandler As EmployeeHandler = New EmployeeHandler
' Get the list of managers
Dim mgrs As New List(Of Manager)
mgrs = eHandler.GetManagerList
cbManager1.DataSource = mgrs
cbManager2.DataSource = mgrs
cbManager1.DataValueField = "Name"
cbManager1.DataTextField = "Name"
cbManager2.DataValueField = "Name"
cbManager2.DataValueField = "Name"
cbManager1.DataBind()
cbManager2.DataBind()
' Get the department name from the label in cell 0
Dim lbl As Label = e.Row.Cells(0).FindControl("lblDepartment")
Dim dept As Department = New Department
dept.Department = lbl.Text
' Pass the department name to the getManager1/2 functions to return the correct manager for that department
Dim mgr1 As Manager = eHandler.getManager1(dept)
Dim mgr2 As Manager = eHandler.getManager2(dept)
' Upper case the manager name to search the DDLs for item
Dim mgr1Name As String = mgr1.Name.ToUpper()
Dim mgr2Name As String = mgr2.Name.ToUpper()
' Find the manager in the DDL and select
cbManager1.SelectedValue = mgr1Name
cbManager2.SelectedValue = mgr2Name
End If
End If
So, I'm having a slight problem with my code.
I was working on a small school project (recreation of book library) and encountered a problem which I cannot get a grasp of.
So, the user can search for a list of books, and after the list is populated (via DataList control), a small button "Book now" (Reserve) appears which user can click and reserve his book.
This is the code for the DataList control that resides in "Search.aspx"
<asp:DataList ID="DataList1" runat="server" DataKeyField="knjigaId" DataSourceID="SearchSqlDataSource" CssClass="searchControl">
<ItemTemplate>
<div class="pictureOfFoundBook">
<asp:Image ID="pictureOfFoundBook_imageLink" runat="server" ImageUrl='<%#"~/GetImage.aspx?knjigaId=" & Eval("knjigaId") & "&img=naslovnica" %>' />
</div>
<div class="descriptionOfFoundBook">
Naziv: <asp:Label ID="Label1" runat="server" Text='<%# Eval("naziv") %>' /><br />
Godina izdanja: <asp:Label ID="Label2" runat="server" Text='<%# Eval("godinaIzdanja") %>' /><br />
Broj stranica : <asp:Label ID="brojStranicaLabel" runat="server" Text='<%# Eval("brojStranica") %>' /><br />
Izdavač: <asp:Label ID="NazivIzdavacaLabel" runat="server" Text='<%# Eval("NazivIzdavaca") %>' /><br />
Vrsta tiskovine : <asp:Label ID="NazivVrsteTiskovineLabel" runat="server" Text='<%# Eval("NazivVrsteTiskovine") %>' /><br />
Kategorija: <asp:Label ID="NazivKategorijeLabel" runat="server" Text='<%# Eval("NazivKategorije") %>' /><br /><br />
<asp:HyperLink ID="foundBookEditHL_adminOnly" runat="server" NavigateUrl='<%# "~/admin/knjigeEdit.aspx?knjigaId=" & Eval("knjigaId") %>'>Uredi knjigu</asp:HyperLink><br />
<asp:Button ID="rezervacijeButton" runat="server" Text="Rezerviraj" OnClick="rezervacijaClick" CommandArgument='<%# Eval("knjigaId") %>'/><br />
<asp:Label ID="rezStatusLabel" runat="server"></asp:Label>
<asp:PlaceHolder ID="rezStatusPlaceholder" runat="server"></asp:PlaceHolder>
</div>
<hr />
</ItemTemplate>
</asp:DataList>
I've set the DataList1 control as a Friend sub so I can access the controls in it from another sub;
Friend Sub DataList1_ItemCreated(sender As Object, e As System.Web.UI.WebControls.DataListItemEventArgs) Handles DataList1.ItemCreated
End Sub
I was trying to do the following; on the click of a button "rezervacijeButton", a function "rezervacijaClick" runs, which populates the table in the database.
Protected Sub rezervacijaClick(sender As Object, e As System.EventArgs)
Dim Conn As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("LocalSqlServer").ToString)
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim sql As New StringBuilder
Dim rezstatus As Label = DataList1.FindControl("rezStatusLabel")
sql.Append("INSERT INTO rezervacije(UserName, knjigaId) VALUES (#UserName, #knjigaId)")
Dim buttonsender As Button = sender
cmd.Parameters.AddWithValue("UserName", User.Identity.Name)
cmd.Parameters.AddWithValue("knjigaId", buttonsender.CommandArgument)
Conn.Open()
cmd.CommandText = sql.ToString
cmd.Connection = Conn
cmd.ExecuteNonQuery()
Conn.Close()
buttonsender.Visible = False
rezstatus.Text = "aaa"
'Try
' rezstatus.Text = "testing..."
'Catch ex As Exception
' exlabel.Text = "POGREŠKA"
' exlabel.ForeColor = Drawing.Color.Red
'End
End Sub
The next thing I wanted to do in the function "rezervacijaClick" was to set the text value of the Label (with ID "rezStatusLabel", which resides inside the DataList1 control) to "SOME TEXT" after the "Reserve" button is clicked.
But after the button click, I get the following error :
Object reference not set to an instance of an object.
Line 21:
Line 22: buttonsender.Visible = False
Line 23: rezstatus.Text = "aaa"
Line 24:
Line 25: 'Try
Your rezstatus object is Nothing (null).
This is happening because you aren't looking in the right place for your label.
Each record of data you bind to the DataList will create a new hierarchy of controls, containers that hold the other controls you have defined in your ItemTemplate.
The immediate descendants of DataList1 will be a collection of DataListItem objects and then you will have your controls inside those.
Since we don't know for sure (unless you know you are only binding one record to the DataList) which DataListItem the desired label will be in, we simply walk backwards up the control tree and find the label from there.
Because you are responding to a button click event in your rezervacijaClick method, the parameter sender will be of type Button and will come from rezervacijeButton, so we can use that information to find your label:
Dim clickedButton As Button = CType(sender, Button) 'convert the sender parameter to the correct type: Button
Dim buttonParent As Control = clickedButton.Parent 'get a reference to the button's parent control
Dim rezstatus As Label = CType(buttonParent.FindControl(""), Label) 'find the label by ID and convert it to a Label as the return type of FindControl is Control
I would recommend that, instead of using the Button click event, you use the DataList.ItemCommand event. It will make your life a lot easier. This event fires whenever a Button is clicked within a row of your DataList control.
This way, you get the index passed in through the DataListCommandEventArgs parameter. then you would just need to update your DataList markup to add the event handler:
<asp:DataList ID="DataList1" runat="server" DataKeyField="knjigaId"
DataSourceID="SearchSqlDataSource" CssClass="searchControl"
ItemCommand="DataList1_ItemCommand" >
And your handler code would look like this:
Protected Sub DataList1_ItemCommand(sender As Object, e As System.EventArgs)
Dim Conn As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("LocalSqlServer").ToString)
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim sql As New StringBuilder
Dim rezstatus As Label = e.Item.FindControl("rezStatusLabel")
sql.Append("INSERT INTO rezervacije(UserName, knjigaId) VALUES (#UserName, #knjigaId)")
Dim buttonsender As Button = e.Item.FindControl("rezervacijeButton")
cmd.Parameters.AddWithValue("UserName", User.Identity.Name)
cmd.Parameters.AddWithValue("knjigaId", buttonsender.CommandArgument)
Conn.Open()
cmd.CommandText = sql.ToString
cmd.Connection = Conn
cmd.ExecuteNonQuery()
Conn.Close()
buttonsender.Visible = False
rezstatus.Text = "aaa"
End Sub
I have found a couple of examples on the internet to do this but really struggling to get it working in VB. (Tried a converter but had mixed results)
I need the selection options of a Dropdownlist to be populated based upon the differing values in the first dropdown list.
Can anyone help with a releativley simple example in VB? Not fussed if the values are "hard coded" in the script. Or a SQL bit that pulls the data from a table
Thanks in advance!
The way it is done is to populate second dropdown in SelectedIndexChanged event of the first dropdown
Example:
Protected Sub ddlCountry_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim CountryID As Integer = Convert.ToInt32(ddlCountry.SelectedValue.ToString())
FillStates(CountryID)
End Sub
Private Sub FillStates(ByVal countryID As Integer)
Dim strConn As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString
Dim con As New SqlConnection(strConn)
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "Select StateID, State from State where CountryID =#CountryID"
cmd.Parameters.AddWithValue("#CountryID", countryID)
Dim objDs As New DataSet()
Dim dAdapter As New SqlDataAdapter()
dAdapter.SelectCommand = cmd
con.Open()
dAdapter.Fill(objDs)
con.Close()
If objDs.Tables(0).Rows.Count > 0 Then
ddlState.DataSource = objDs.Tables(0)
ddlState.DataTextField = "State"
ddlState.DataValueField = "StateID"
ddlState.DataBind()
ddlState.Items.Insert(0, "--Select--")
Else
lblMsg.Text = "No states found"
End If
End Sub
With html source as so:
<asp:DropDownList ID="ddlState" runat="server" AutoPostBack="True">
</asp:DropDownList>
<asp:DropDownList ID="ddlCountry" runat="server"
AutoPostBack="True" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged">
</asp:DropDownList>
You could accomplish this declaratively in the ASPX page like this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:myConnString %>" SelectCommand="SELECT id, name FROM planets"></asp:SqlDataSource>
<asp:DropDownList ID="ddlPlanets" AutoPostBack="true" DataTextField="name" DataValueField="id" DataSourceID="SqlDataSource1" runat="server" AppendDataBoundItems="true" />
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:myConnString %>" SelectCommand="SELECT planetid, name FROM moons" FilterExpression="planetid = '{0}'">
<FilterParameters>
<asp:ControlParameter Name="planetid" ControlID="ddlPlanets" PropertyName="SelectedValue" />
</FilterParameters>
</asp:SqlDataSource>
<asp:DropDownList ID="ddlMoons" DataTextField="name" DataValueField="planetid" DataSourceID="SqlDataSource2" runat="server" />
Your best option will be to capture the SelectedIndexChanged event on the first dropdownlist, examine what the current value of that dropdownlist is, and then use that to clear and then populate the items in the second dropdownlist. When you do so, remember to set the AutoPostBack property of the first DropDownList to "true".