.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Fill a Listbox with value selected from a Dropdownlist

Posted By:      Posted Date: September 08, 2010    Points: 0   Category :ASP.Net
Hi, Maybe the question has already be posted, but I didn't find it.I have in my web page two controls: a dropdownlist and a listboxMy goal is to fill the listbox with values from my database depending on what I have selected in my dropdownlist.I wouldlike to use the CascadingDropDown component for that. Is that possible ??(I tried on my own and I get this error messageException Details: System.InvalidCastException: Unable to cast object of type 'System.Web.UI.WebControls.ListBox' to type 'System.Web.UI.WebControls.DropDownList'.I think it's when i tried to fill the listbox with this function:[WebMethod] public CascadingDropDownNameValue[] GetAppliForDomain(string knownCategoryValues, string category) { int domainID; //this stringdictionary contains has table with key value pair of country and countryID StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues); if (!kv.ContainsKey("Domain") || !Int32.TryParse(kv["Domain"], out domainID)) { throw new ArgumentException("Couldn't find Domain."); }; SqlConnection con = new SqlConnection(strConnection); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandType = System.Data.CommandType.Text

View Complete Post

More Related Resource Links

Working with DropDownList and ListBox Controls in ASP.NET

"In my application i am using dropdownlist to display all categories from a table. When the user clicks this control I display all records in that category. Category table also contains column called color.

I wanted display some categories in dropdown list different color and others in different color using ASP.NET."-Anonymous

how can i display the selected value of dropdownlist from edittemplate to label from itemtemplate?


I have a detailsview with a dropdownlist in it. the detailsview is connected to a database table(employees having the following fields: id-smallint,name-nvarchar, departmnet-smallint). the ddl is connected to another table (departments with the following fields: id-smallint, departmentName-nvarchar). the ddl is in the edititemTempalte of the department field. My goal is to display in  the itemtemplate the departmentName (the selected value from the edititemtemplate ). How can I do this? Doyou have any ideas?

thanks a lot

dropdownlist - default value is not 'selected value'

i have created a dropdown list that is populated from a sqlserver datasource. i have a separate sql command which uses the dropdownlist.selected value as a parameter and returns the command value to a label.  it mostly works fine but with one problem. when the page loads, the label value is null, because it doesn't seem to treat the dropdownlist default value as a selected value. when i use the dropdownlist to select a value, this is fine and the label begins to display the expected value. is there anyway I can make the default value when the page is loaded act like a manually selected value, so the label control never displays a null value?

ASP.Net MVC Dropdownlist and selected value problem

I was able to create a dropdownlist for my MVC project, but the value is not selected as  selected value on the dropdownlist. It just shows whole county list from the first.The value is from database. I tried find it from previous post, but it was quite confusing. Please, suggest me for any idea. Controller Code public ActionResult Edit(int i) {      var items = new SelectList(db.MST_COUNTRies.ToList(), "COUNTRY_ID", "COUNTRY_NM");      ViewData["MST_COUNTRies"] = items; } View Code <p>     <%= Html.DropDownList("COUNTRY_ID", (SelectList)ViewData["MST_COUNTRies"])%> </P>I was able to create a dropdownlist for my MVC project, but the value is not selected as  selected value on the dropdownlist. It just shows whole county list from the first.The value is from database. I tried find it from previous post, but it was quite confusing. Please, suggest me for any idea.Controller Codepublic ActionResult Edit(int i){     var items = new SelectList(db.MST_COUNTRies.ToList(), "COUNTRY_ID", "COUNTRY_NM");     ViewData["MST_COUNTRies"] = items;}View Code<p>    <%= Html.DropDownList("COUNTRY_ID", (SelectList)ViewData["MST_COUNTRies"])%></P>

Trap Selected Index change event of listbox using Javascript.

Hi All, This is reagarding listbox selection. I have a list box with multi select option. I want to trap the selected index change event of Listbox through javascript. Item of list box can be selected using Click of mouse and also the keyboard up down key with shift. I tried onclick event to bind the javascript function. It works fine if I select by mouse, but it doesen't work for up/down key of keyboard. Thanks, Naveen

How can I make the listbox scroll to the selected item

Hi All, I have a textbox that searches the listbox below it and selects the text that I types in the textbox. Now although the item is selected in the listbox I have to scroll to the end to see if the item is selected ornot IS there a way that I can make the list box scroll to the selected item?    

How to get item selected in dropdownlist

I'm searching and trying now for the last couple of hours, so I thought the community might help.I'm filtering the rows in a gridview using a ddlDate. Now, I want to request this selected item.But: When I load the page without clicking in the DropDownList, the ddlDate.SelectedValue is empty, and the ddlDate.SelectedItem.Text.ToString() gives a NullReferenceException.Is there any way to fix this without using a listbox?

Fetching DropDownList Selected Value

I'm having issues getting the selecteditems and value after Databinding a dropdown list.  I have a button event with dropdownlist2.Selecteditem.text, but will always get the "-- Select --" as the SelectedItem.text ?  Anybody know why this is happening ?   Dim conn As New SqlConnection '("xxxxxx") conn.ConnectionString = ConfigurationManager.ConnectionStrings("PostAdSqlServer").ToString Dim query As String = ("SELECT [CategoryId], [Name] FROM [Category]") Dim cmd As New SqlCommand(query, conn) cmd.Connection.Open() Dim ddlValues As SqlDataReader ddlValues = cmd.ExecuteReader() DropDownList2.DataSource = ddlValues DropDownList2.DataValueField = "CategoryId" DropDownList2.DataTextField = "Name" DropDownList2.DataBind() DropDownList2.Items.Insert(0, "-- Select --") cmd.Connection.Close() cmd.Connection.Dispose()    

dropdownlist selected item problum

In gridview we have edit button whenever user click edit button i want to show particular data of dropdownlist as a selected data that is selected by user as a selected text of dropdownlistis there any solution ???

ListBox.SelectedItem stuck at whatever is first selected and other strange ListBox behavior

Hi, I've built a List<Participant> (Participant being my custom type) and assigned this to ListBox.ItemsSource. (I'm aware this is more the Windows Forms way than the WPF way of databinding, but I'd still like to understand what's going on here - even though suggestions on how to perform my task in a more WPF-y way are also welcome.) I've set ListBox.SelectionMode to Single, and attached an event handler to the SelectionChanged event. In this handler, I dump the SelectedIndex and SelectedItem to debug output. Contrary to my expectation, 1) SelectedIndex is always -1. This isn't really causing me any trouble, but it's certainly not what I'd expect. 2) SelectedItem refers to the correct object the first time (in the windows lifetime) I select an item, but then keeps referring to this first-selected item regardless of whether I deselect (by clicking the item again while holding down the CTRL key) or select some other item. 3) If I keep clicking around and scrolling a bit (the list has ~320 items) within the list, now and then the list suddenly displays a bunch of items - sometimes many in a row, sometimes non-contiguous items, but it seems always "nearby" items! - as if they were selected. The list keeps firing the SelectionChanged event, but SelectedIndex is forever -1 and SelectedItem (and SelectedValue) always refers to whatever I had selected the fir

Selected Option from dropdownlist

 I need to figure out a way to modify the style property of a div on my page so that when a certain item ("Not shown - please quote") on a few different dropdownlists are selected,  the div style is set to "display: none". The dropdownlist gets generated dynamically and the amount of dropdownlists varys for each product. I've named the class via the cssclass property in the dropdownlist template usercontrol to be "dropDownClass".Here is my code for this page: <div id="ProductControls"> <div id="ProductOptions"> <div id="ctl00_MainContentHolder_VariantsDisplay_VariantsPanel" class="variantsdisplay"> <table> <tr class="dropdownlist"> <td class="choicelabel"><span id="ctl00_MainContentHolder_VariantsDisplay_modifierTemplate1_InputLabel">Color</span></td> <td class="choicefield"><select name="ctl00$MainContentHolder$VariantsDisplay$modifierTemplate1$ModifierList" onchange="javascript:setTimeout('__doPostBack(\'ctl00$MainContentHolder$VariantsDisplay$modifierTemplate1$ModifierList\',\'\')', 0)" id="ctl00_MainContentHolder_VariantsDisplay_modifierTemplate1_ModifierList" clas

How to Capture a DropDownList Selected Index Change Event

I have a gridview that receives data based on selection from a primary dropdownlist object. Works. Within the gridview, there is a dropdownlist whose selected index is based on the query from the primary dropdownlist. Works. Problem. How do I force the used to  change whatever value that the dropdownlist contains after they make their initial selection from the primary dropdownlist; except the default value of "Please make a selection". Gridview, contains a checkbox which drives whether a selected row is inserted into the data base. The databind in done using an ObjectDataSource on the presentation page, not in the code behind.   Thank you.   Ayomide 

hoq to fill gridview dropdownlist from another db table

Hi, I have a gridview which gets its data from a database table now i ghave added a dropdownlist to this gridview but this dropdown should get the data from another table and should set its value automatically with a foreign key from the  gridview i have added the code like below in my rowDatabound but it just loads 1 field and then how should i get the selectedValue according to the gridview id field?? Protected Sub Friends_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)             If e.Row.RowType = DataControlRowType.DataRow Then                 Dim conn As New SqlConnection(HttpRuntime.Cache("con"))                Dim sql As String = "select ID,ListName from FriendList order by ListName asc"                Dim cmd As New SqlCommand(sql, conn)                cmd.CommandType = CommandType.Text                conn.Open()             &

dropdownlist selected value problem

i have dropdownlist<%= Html.DropDownListFor(model => model.SchoolDistrict,Model.sSchoolDistrict) %>To Poulate this value i have below code in controllerslist = new SelectList(list, "ID", "Name", selected);but what ever selected value i pass didnot shown in ddl

How to set selected value on asp:dropdownlist?

I am not a dev, I am sharepoint admin.  I have a SPD page with an asp:dropdownlist that uses a sqldatasource to populate the drop-down list.  This list does a postback which allows the user to select an item in the list and the rest of the page is generated based on the selection.  The user has options which include navigating away to another page with the id from the select passed as a query string to the new page.  This all works fine.  I am not using any bound fields or SSO for this because I need to execute a stored proc on the server to obtain the items populating the drop-down list. What I need to do now is allow the user to navigate back to the original page, however I want the original page to display using the same id passed in a query string rather than the default value of the datasource.  (so they don't have to select the same item from the drop-down list again after returning to the original page)  I can't seem to find a way to do this.  When I add a SelectedValue to the asp:DropDownList I get an error saying the Bind is not allowed.  I "thought" that I could add a querystring parameter to the datasource and use it as the selected value, but have not been successful.  I don't know if I am just doing it wrong or if this concept is wrong.  Below is the relevant code for the dro

auto-scrolling to the selected item in a listbox



I have a listbox which is populated with items at Page_Load and has 5 items visible at a time.  Then there is a textbox where the user types some characters. On keyup event of the textbox  my code searches the listbox for the entered value and selects the item closest to the entered value. However the selected item appears as the 5th item in the listbox. I want it to be the 1st item displayed.

Any ideas ??


Adding Multiple Selected Values to ListBox Dynamically


I have a ListBox control that gets populated from a database like this:

For Each gvr As GridViewRow In GridView1.Rows
                Dim lb As ListBox = CType(gvr.FindControl("SectionsListBox"), ListBox)
                For Each sect As String In sectionlist


Then the selected values also get populated like this:

For Each gvr As GridViewRow In GridView1.Rows
                Dim lb As ListBox = CType(gvr.FindControl("SectionsListBox"), ListBox)
                Dim faqid As Integer = gvr.Cells(0).Text
                selectedlist = oCMS.getFAQSections(faqid)
                For Each sect As String In selectedlist
                    lb.SelectedValue += sect


I need to have multiple selections, but I cannot get it to select multiple values with this line "lb.SelectedValue += sect".  The listbox has been set in aspx to allow multiple selections.


ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend