DropDownList Database - asp.net

I have a DB and a DropDownList, but this always only shows System.Data.DataRowView. What can I do? My code:
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:campingConnectionString2 %>" ProviderName="<%$ ConnectionStrings:campingConnectionString2.ProviderName %>" SelectCommand="SELECT Distinct LandDE FROM campingplatz ORDER BY LandDE ASC"></asp:SqlDataSource>

You need to set the DataTextField and DataValueField properties for the list, so it knows what columns in the DataRow to look at.

Ok, there are always quite a few ways to do this.
I often don't use a "datasource" imbeeded in the markup. They are often less then easy to deal with. (but, I'll often use the wizard to setup the dropdown, as it does setup the columns etc.
but, lets say we have two combo boxes. One for City, and then when you select the city then the 2nd combo box fills with hotels from that city.
So we have this markup:
<div style="font-size:x-large">
Select City:
<asp:DropDownList ID="cboCity" runat="server" width="150px" style="margin-right:25px"
DataValueField="City" DataTextField="City"
AutoPostBack="true" OnTextChanged="cboCity_TextChanged">
</asp:DropDownList>
Select Hotel:
<asp:DropDownList ID="cboHotels" runat="server" width="150px"
DataValueField="ID" DataTextField="HotelName">
</asp:DropDownList>
</div>
And then some code to fill the first combo box, and the 2nd one like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' load combo box (City)
Using cmdSQL As SqlCommand = New SqlCommand("SELECT City from tblCity ORDER BY City",
New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
cboCity.DataSource = cmdSQL.ExecuteReader
cboCity.DataBind()
' add blank row to combo
cboCity.Items.Insert(0, "")
End Using
End If
End Sub
Protected Sub cboCity_TextChanged(sender As Object, e As EventArgs)
' fill hotels combo based on city
Dim strSQL As String
strSQL = "SELECT ID, HotelName FROM tblHotels WHERE City = #City ORDER BY HotelName"
Using cmdSQL As SqlCommand = New SqlCommand(strSQL, New SqlConnection(My.Settings.TEST3))
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = cboCity.SelectedValue
cmdSQL.Connection.Open()
cboHotels.DataSource = cmdSQL.ExecuteReader
cboHotels.DataBind()
End Using
End Sub
So now we get say this:
So we did set autopostback = true for the first combo, and when the user selected the city, then we use that city value to fill the 2nd combo with a list of hotels from that city.

Unfortunately, I do not understand that. Can you do that on my code, please?
<asp:DropDownList ID="LandList" runat="server" DataSourceID="SqlDataSource2" AutoPostBack="True" DataMember="DefaultView" DataTextField="LandDE" DataValueField="LandDE">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:campingConnectionString2 %>" ProviderName="<%$ ConnectionStrings:campingConnectionString2.ProviderName %>" SelectCommand="SELECT Distinct LandDE FROM campingplatz ORDER BY LandDE ASC"></asp:SqlDataSource>

Related

Gridview ASP.NET Changing values of the second drop down list based on value selected of first drop down in same column

<asp:SqlDataSource ID="sdsUsers" runat="server"
ConnectionString="<%$ ConnectionStrings:Org Name %>"
SelectCommand="select full_name, user_id from dbo.Users where entity_state_id = 1">
</asp:SqlDataSource>
<asp:SqlDataSource ID="sdsOrganizations"
runat="server"
ConnectionString="<%$ ConnectionStrings:Org Name %>"
SelectCommand="select organization_name from dbo.Organizations where Organization_Name like '%CDM%'">
</asp:SqlDataSource>
<asp:TemplateField HeaderText="Status" SortExpression="type">
<ItemTemplate>
<%# Eval("Status")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Assigned To" SortExpression="type">
<ItemTemplate>
<asp:DropDownList ID="ddlOrganization" runat="server" DataSourceID="sdsOrganizations"
DataTextField="organization_name" AutoPostBack="true" AppendDataBoundItems="true">
<asp:ListItem Text="Not Assigned" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlUsers" runat="server" DataSourceID="sdsUsers" DataTextField="full_name" DataValueField="user_id" AutoPostBack="true" AppendDataBoundItems="true">
<asp:ListItem Text="Not Assigned" Value="0"></asp:ListItem>
</asp:DropDownList>
</asp:TemplateField>
Good afternoon , I need to populate users list from the database based on the organization they select in gridview.
How can i do that?
Thanks
Ok, assuming a grid like this (with two combo box).
In this example, we have some people, and we want them to select city, and then select a hotel from for the given city (so we cascade from City cbo to hotel list for 2nd combo).
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" Width="30%" >
<Columns>
<asp:BoundField DataField="Firstname" HeaderText="Firstname" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:TemplateField HeaderText="Select Hotel City">
<ItemTemplate>
<asp:DropDownList ID="cboCity" runat="server" Width="120px"
DataTextField = "City"
DataValueField = "City"
AutoPostback="true"
OnSelectedIndexChanged="cboCity_SelectedIndexChanged" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Select Hotel">
<ItemTemplate>
<asp:DropDownList ID="cboHotels" runat="server" Width="210px"
DataValueField ="ID"
DataTextField ="HotelName"
></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Our code to load is thus this:
Dim rstCity As New DataTable
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid
End If
End Sub
Sub LoadGrid()
' load up City list for combo box
rstCity = MyRst("SELECT City from City ORDER BY City")
' load up the grid
GridView1.DataSource = MyRst("SELECT * from People ORDER BY FirstName")
GridView1.DataBind()
End Sub
Public Function MyRst(strSQL As String) As DataTable
Dim rstData As New DataTable
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
And our result is this:
Ok, so we have this for our first city cbo box:
<asp:TemplateField HeaderText="Select Hotel City">
<ItemTemplate>
<asp:DropDownList ID="cboCity" runat="server" Width="120px"
DataTextField = "City"
DataValueField = "City"
AutoPostback="true"
OnSelectedIndexChanged="cboCity_SelectedIndexChanged" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
So, on the index changed event for this combo, after we select the city, then we fill the 2nd combo box with hotels for that city.
That code looks like this:
Protected Sub cboCity_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim cboCity As DropDownList = sender
' get current grid row
Dim gRow As GridViewRow = cboCity.NamingContainer
' filter hotels to current city
Dim strCity As String = cboCity.SelectedItem.Text
Dim strSQL = "SELECT * from tblHotels WHERE CITY = '" & strCity & "' ORDER BY HotelName"
Dim cboHotels As DropDownList = gRow.FindControl("cboHotels")
cboHotels.DataSource = MyRst(strSQL)
cboHotels.DataBind()
cboHotels.Items.Insert(0, New ListItem("", ""))
End Sub
So, on cbo change, we get the current row, get the 2nd cbo box, and then simply fill it out with ONLY a city list of hotels based on the first cbo box of city
There is of course some more moving parts we could (should add).
For example, while we save the hotel name (cbo box), we don't save the city value - we don't have to.
However, this means on FIRST grid load, in theory we have to:
Check if the hotel is loaded, and if yes, THEN SET the first combo box based on that selection. (or we could leave all city cbo blank on start up - but in theory, we should check for hotel, and if yes, then get the city for the hotel, and then set the city cbo box. This is actually more work then the above cascading code, since we have to query hotel to get the city, and then set the city cbo box based on that.
But, here is that code anyway - we put it in the row data bind event, since on first gv load, we have to setup the city cbo box (and it is not bound to any data - and note saved in the database - it is only a selector to filter hte hotel selection (which is saved in the database ).
So, that code - a bit messy, but in theory is required.
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
' get the data bind row data
Dim gData As DataRowView = e.Row.DataItem
' load the city combo box - full city list
Dim cboCity As DropDownList = e.Row.FindControl("cboCity")
cboCity.DataSource = rstCity
cboCity.DataBind()
' add blank row for city
cboCity.Items.Insert(0, New ListItem("", ""))
' now load Hotel combo box (if we have one!!)
Dim cboHotels As DropDownList = e.Row.FindControl("cboHotels")
If Not IsDBNull(gData("Hotel_id")) Then
' get the one hotel record - we need the city from that hotel
' to set the city cbo
Dim rstOneHotel As DataRow = MyRst("SELECT * From tblHotels where ID = " & gData("Hotel_id")).Rows(0)
Dim strHotelCity As String = rstOneHotel("City")
' set the city filter cbo to correct city
cboCity.SelectedValue = strHotelCity
' load hotel combo box only with current city list
Dim strSQL As String = "Select ID,HotelName From tblHotels WHERE City = '" &
strHotelCity & "' ORDER BY HotelName"
cboHotels.DataSource = MyRst(strSQL)
cboHotels.DataBind()
' set hotels combo to current selected
cboHotels.SelectedValue = gData("Hotel_id")
End If
End If
End Sub

Change textbox value when selecting dropdownlist value

I have a dropdownlist control that shows the primary key from a table called model, and a textbox that should show another value(a foreign key) from that same table when I use the dropdownlist.
Both PK and FK have a single value.
Since I didn't have a clue how to do this, I used a search method that should be called everytime someone selects a new value from the dropdownlist.
Search code:
Public Function searchArea(ByVal model As String) As String
Dim mycon As New Connection
Using connection As New SqlConnection(mycon.GetConnectionString())
Using command As New SqlCommand()
command.Connection = connection
command.CommandType = CommandType.Text
command.CommandText = "SELECT area FROM model WHERE model= #model"
command.Parameters.AddWithValue("#model", model)
connection.Open()
Dim dataReader As SqlDataReader = command.ExecuteReader()
If (dataReader.Read()) Then
Return dataReader.ToString(0)'this query should always have a single value
End If
Return "Nothing"
End Using
End Using
End Function
Event code:
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles DropDownList1.SelectedIndexChanged
Dim objModel As New ModelDAO 'the class where the method is
TextBox9.Text = objModel.searchArea(DropDownList1.Text)
End Sub
.
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True"
DataSourceID="SqlDataSource1" DataTextField="MODEL" DataValueField="MODEL">
<asp:ListItem Text="-Select-" Value="" />
</asp:DropDownList>
<asp:TextBox ID="TextBox9" runat="server" Enabled="False" Height="24px"
Width="219px"></asp:TextBox>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DBUserInterfaceConnectionString %>"
SelectCommand="SELECT [MODEL] FROM [MODEL]">
</asp:SqlDataSource>
But as I thought, it doesn't work, can you help me please?
EDIT: Thanks, now it triggers, but I'm getting the value: 'S' that value doesn't belong to my table.Can you tell me if my search method is ok?
Try to add this
<asp:DropDownList ID="DropDownList1"
runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
.....
</asp:DropDownList>
Try to Load datareader into datatable and than use it to print data into the textbox..
Thank you everyone, I solved it with this:
Return dataReader.GetString(0)
instead of:
Return dataReader.ToString(0)
It was just a type conversion problem.

Dropdown list to attach to repeater that will filter gridview

This post is similar to one I have posted before about a dropdown filtering results in a gridview. Well now I need this dropdown to attach itself to a repeater that will filter results into a gridview. I have tried rptLetters.DataBind() in the code behind of the dropdown list, but that doesn't seem to be changing any of the letters at the top of the page when I click on different items in the dropdown list.
The screenshot doesn't show enough of the products, but in this case it skips from G to L, and in the repeater the letters between G and L are still shown. I need to be able to get that repeater to recognize the letters that start each of the products associated with the company chosen.
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server"><br /><br />
<asp:linkbutton id="btnAll" runat="server" text="ALL" onclick="btnAll_Click" />
<asp:repeater id="rptLetters" runat="server" datasourceid="dsLetters">
<headertemplate>
|
</headertemplate>
<itemtemplate>
<asp:linkbutton id="btnLetter" runat="server" onclick="btnLetter_Click"
text='<%#Eval("Letter")%>' />
</itemtemplate>
<separatortemplate>
|
</separatortemplate>
</asp:repeater>
<asp:sqldatasource id="dsLetters" runat="server" connectionstring="<%$
ConnectionStrings:ProductsConnectionString %>"
selectcommand="SELECT DISTINCT LEFT(ProductName, 1) AS [Letter] FROM [Product]">
</asp:sqldatasource>
<br /><br />Choose Company:
<asp:DropDownList ID="ddlCompany" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddlCompany_SelectedIndexChanged">
<asp:ListItem Value="8">3rd Party</asp:ListItem>
<asp:ListItem Value="4">BestDirect Securities</asp:ListItem>
<asp:ListItem Value="18">Generic</asp:ListItem>
<asp:ListItem Value="5">PFG Precious Metals</asp:ListItem>
<asp:ListItem Value="1" Selected="True">PFGBest</asp:ListItem>
<asp:ListItem Value="2">SFO</asp:ListItem>
<asp:ListItem Value="6">Traders Press</asp:ListItem>
<asp:ListItem Value="3">W&A Publishing</asp:ListItem>
</asp:DropDownList>
<asp:gridview id="gvProducts" runat="server" AutoGenerateColumns="False"
datakeynames="ProductID,CompanyID" datasourceid="dsProductLookup"
style="margin-top: 12px;">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="ProductID"
DataNavigateUrlFormatString="Product/Default.aspx?ID={0}"
DataTextField="ProductName" HeaderText="Product Name"
SortExpression="ProductName" />
</Columns>
</asp:gridview>
<asp:sqldatasource id="dsProductLookup" runat="server"
Connectionstring="<%$ ConnectionStrings:ProductsConnectionString %>"
SelectCommand="SELECT DISTINCT Product.ProductName, Product.ProductID, Company.CompanyID
FROM Product
LEFT JOIN CompanyLink
ON Product.ProductID = CompanyLink.ProductID
LEFT JOIN Company
ON CompanyLink.CompanyID = Company.CompanyID
ORDER BY Product.ProductName">
</asp:sqldatasource>
<asp:SqlDataSource ID="dsCompanyFilter" runat="server"
ConnectionString="<%$ ConnectionStrings:ProductsConnectionString %>"
SelectCommand="SELECT [CompanyName], [CompanyID]
FROM [Company]
ORDER BY CompanyName">
</asp:SqlDataSource>
</asp:Content>
Protected Sub btnAll_Click(sender As Object, e As EventArgs)
gvProducts.DataBind()
End Sub
Protected Sub btnLetter_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim btnLetter As LinkButton = TryCast(sender, LinkButton)
If btnLetter Is Nothing Then
Return
End If
dsProductLookup.SelectCommand = [String].Format("SELECT ProductID, ProductName
FROM [Product]
WHERE ([ProductName] LIKE '{0}%')
ORDER BY [ProductName]",
btnLetter.Text)
dsProductLookup.SelectParameters.Clear()
Dim controlParam As ControlParameter = New ControlParameter
controlParam.ControlID = "rptLetters"
controlParam.DefaultValue = "-1"
controlParam.Name = "CompanyID"
controlParam.PropertyName = "Container.ItemIndex"
controlParam.Type = TypeCode.String
dsProductLookup.SelectParameters.Add(controlParam)
End Sub
Protected Sub ddlCompany_SelectedIndexChanged(ByVal sender As Object, ByVal e As
System.EventArgs) Handles ddlCompany.SelectedIndexChanged
rptLetters.DataBind()
'SELECT statement to update letter repeater
dsLetters.SelectCommand = "SELECT DISTINCT LEFT(ProductName, 1) AS [Letter]
FROM Product, CompanyLink, Company
WHERE Product.ProductID = CompanyLink.ProductID
AND CompanyLink.CompanyID = Company.CompanyID
AND Company.CompanyID = #CompanyID"
dsLetters.SelectParameters.Clear()
'declaring scalar variable #CompanyID
Dim cp As ControlParameter = New ControlParameter
cp.ControlID = "rptLetters"
cp.DefaultValue = "-1"
cp.Name = "CompanyID"
cp.PropertyName = "SelectedValue"
cp.Type = TypeCode.Int32
dsLetters.SelectParameters.Add(cp)
'SELECT statement to update Gridview based on dropdown list
dsProductLookup.SelectCommand = "SELECT Company.CompanyName, Company.CompanyID,
Product.ProductName, Product.ProductID
FROM Company INNER JOIN CompanyLink
ON Company.CompanyID = CompanyLink.CompanyID
INNER JOIN Product
ON CompanyLink.ProductID = Product.ProductID
WHERE Company.CompanyID = #CompanyID
ORDER BY Product.ProductName"
dsProductLookup.SelectParameters.Clear()
'declaring scalar variable #CompanyName
Dim controlParam As ControlParameter = New ControlParameter
controlParam.ControlID = "ddlCompany"
controlParam.DefaultValue = "-1"
controlParam.Name = "CompanyID"
controlParam.PropertyName = "SelectedValue"
controlParam.Type = TypeCode.Int32
dsProductLookup.SelectParameters.Add(controlParam)
End Sub
UPDATE: Working code posted below. The repeater doesn't work like a regular control so I added a hidden dropdown list to do the dirty work for the repeater. Thanks for the help!
<asp:DropDownList ID="ddlLetters" runat="server" Visible="False" DataSourceID="dsLetters">
</asp:DropDownList>
Protected Sub ddlLetters_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
rptLetters.DataBind()
'SELECT statement to update letter repeater
dsLetters.SelectCommand = "SELECT DISTINCT LEFT(ProductName, 1) AS [Letter]
FROM Product, CompanyLink, Company
WHERE Product.ProductID = CompanyLink.ProductID
AND CompanyLink.CompanyID = Company.CompanyID
AND Company.CompanyID = #CompanyID"
'declaring scalar variable #CompanyID
dsLetters.SelectParameters.Clear()
Dim cp As ControlParameter = New ControlParameter
cp.ControlID = "rptLetters"
cp.DefaultValue = "-1"
cp.Name = "CompanyID"
cp.PropertyName = "ClientIDMode"
cp.Type = TypeCode.Decimal
dsLetters.SelectParameters.Add(cp)
End Sub
I believe the issue is that you are not updating the dsLetters SelectCommand when the user selects a new company. Right now, it selects all products without taking the selected company into account. You should be able to modify the select command in ddlCompany_SelectedIndexChanged.

Dropdown list to filter gridview

I would like my gridview to be filtered by the dropdown list I have. It is pulling specific information from the database, so when you choose a value from the dropdown list, it should search through all the records and find only records with the ddl value in them.
The code that I am using in the codebehind for the SelectedIndexChanged is not right though. I get an error message saying 'Value' is not a member of 'Integer'. This is on the line dsCompanyFilter.SelectParameters.Add
It probably has something to do with the gridview not tying to the dropdown list properly, but I am not sure how to fix that code. Please help!
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server"><br /><br /><br />
<asp:linkbutton id="btnAll" runat="server" text="ALL" onclick="btnAll_Click" />
<asp:repeater id="rptLetters" runat="server" datasourceid="dsLetters">
<headertemplate>
|
</headertemplate>
<itemtemplate>
<asp:linkbutton id="btnLetter" runat="server" onclick="btnLetter_Click"
text='<%#Eval("Letter")%>' />
</itemtemplate>
<separatortemplate>
|
</separatortemplate>
</asp:repeater>
<asp:sqldatasource id="dsLetters" runat="server" connectionstring="<%$
ConnectionStrings:ProductsConnectionString %>"
selectcommand="SELECT DISTINCT LEFT(ProductName, 1) AS [Letter] FROM [Product]">
</asp:sqldatasource>
Filter By Company:<asp:DropDownList ID="ddlCompany" runat="server"
DataSourceID="dsCompanyFilter" DataTextField="CompanyName" DataValueField="CompanyID">
</asp:DropDownList>
<asp:gridview id="gvProducts" runat="server" AutoGenerateColumns="False"
datakeynames="ProductID" datasourceid="dsProductLookup"
style="margin-top: 12px;">
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="ProductName"
SortExpression="ProductName" />
</Columns>
</asp:gridview>
<asp:sqldatasource id="dsProductLookup" runat="server" connectionstring="<%$
ConnectionStrings:ProductsConnectionString %>"
Selectcommand="SELECT ProductID, ProductName FROM [Product] ORDER BY [ProductName]">
</asp:sqldatasource>
<asp:SqlDataSource ID="dsCompanyFilter" runat="server"
ConnectionString="<%$ ConnectionStrings:ProductsConnectionString %>"
SelectCommand="SELECT [CompanyName], [CompanyID] FROM [Company]">
</asp:SqlDataSource>
</asp:Content>
This code filters the results in the gridview by Letter and the Dropdown. The problem is with the dropdown list filtering the gridview.
Protected Sub btnLetter_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim btnLetter As LinkButton = TryCast(sender, LinkButton)
If btnLetter Is Nothing Then
Return
End If
dsProductLookup.SelectCommand = [String].Format("SELECT ProductID, ProductName
FROM [Product]
WHERE ([ProductName] LIKE '{0}%')
ORDER BY [ProductName]", btnLetter.Text)
End Sub
This is the part that has the problem. I now get the error, must declare the scalar variable #CompanyID
Protected Sub ddlCompany_SelectedIndexChanged(ByVal sender As Object, ByVal e As
System.EventArgs) Handles ddlCompany.SelectedIndexChanged
dsProductLookup.SelectCommand = "SELECT ProductName, CompanyID, CompanyName
FROM Product, Company
WHERE CompanyID = #CompanyID
ORDER BY ProductName"
dsProductLookup.SelectParameters.Add("#CompanyID", DbType.Int32,
ddlCompany.SelectedValue)
End Sub
Deleted my previous answer.
Actually try the following :
dsProductLookup.SelectParameters.Add("#ProductID",
DbType.Int32, ddlCompany.SelectedValue)
No assignment to value as it is part of the Add. Noticed this when I tried to compile a test of my previous answer which didn't work.
EDIT: I tried the above code and it worked (did it in C#) but changed it to use DbType.Int32 for second param.
dsProductLookup.SelectParameters.Add("#ProductID", SqlDbType.Int).Value
It looks to me ilke the .Add() method is returning an int, to which .Value is not a property.
Confirmed it to make sure:
This is from the MSDN: Should help.
http://msdn.microsoft.com/en-us/library/w1kdt8w2.aspx
I'm guessing here -- I don't use SqlDataSources -- but it looks like SelectParameters.Add takes three parameters. What happens when change this:
dsProductLookup.SelectParameters.Add("#ProductID", SqlDbType.Int).Value = ddlCompany.SelectedValue
to this:
dsProductLookup.SelectParameters.Add("#ProductID", DbType.Int32, ddlCompany.SelectedValue)
or this:
dsProductLookup.SelectParameters.Add("#ProductID", TypeCode.Int32, ddlCompany.SelectedValue)

Populate DropdownList based upon other DropDownList VB

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".

Resources