Click here to Skip to main content
15,881,819 members
Everything / ListBox

ListBox

ListBox

Great Reads

by Nilay M Joshi
Multiselect Combobox - Custom control for WPF
by Magnus_
public static void RemoveSelected(this ListControl source){ foreach (var item in source.Items.Cast().Where(li => li.Selected).ToList()) source.Items.Remove(item);}protected void btnRemove_Click(object sender, EventArgs e){ lstCity.RemoveSelected();}
by Evren Yortuçboylu
A checkbox list jQuery UI widget with real time filtering functionality explained
by Paul_Williams
The difference between ListBox and CheckedListBox DataBinding.

Latest Articles

by Martin Henke (1971)
Edit Metadata for folders by using desktop.ini features
by Nilay M Joshi
Multiselect Combobox - Custom control for WPF
by Michael Shpilt
A WPF tutorial on how to create FilteredListView: A ListView custom control with search filter that uses Throttling.
by davekahn
An easy way to control the lists of options in multiple related SELECT controls

All Articles

Sort by Score

ListBox 

26 May 2021 by Nilay M Joshi
Multiselect Combobox - Custom control for WPF
21 Nov 2010 by OriginalGriff
Try:string search = textBox1.Text;listBox2.Items.Clear();foreach (string val in listBox1.Items) { if (val.StartsWith(search)) { listBox2.Items.Add(val); } }
14 May 2010 by Magnus_
public static void RemoveSelected(this ListControl source){ foreach (var item in source.Items.Cast().Where(li => li.Selected).ToList()) source.Items.Remove(item);}protected void btnRemove_Click(object sender, EventArgs e){ lstCity.RemoveSelected();}
21 Jan 2011 by Manfred Rudolf Bihy
Try this:public ListBox AddItemsToListBoxFromString(ListBox lb, String strItems, char[] separators){ String[] items = strItems.Split(separators); foreach(String item in items) { lb.Items.Add(item.Trim()); } return lb;}A typical call from a code...
23 Jan 2011 by Manfred Rudolf Bihy
Please try ListView.EnsureVisible(int index). See here: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.ensurevisible.aspx[^]
18 Sep 2012 by Evren Yortuçboylu
A checkbox list jQuery UI widget with real time filtering functionality explained
17 Jan 2014 by Jochen Arndt
You may use GetScrollBarInfo()[^]:bool bVisible = false;SCROLLBARINFO SbVert;SbVert.cbSize = sizeof(SbVert);if (GetLBox().GetScrollBarInfo(OBJID_VSCROLL, &SbVert)){ // Index 0 of rgstate is the scrollbar itself // See SCROLLBARINFO in the MSDN if (0 == sbi.rgstate[0] &...
26 Dec 2016 by OriginalGriff
Well...namespaces called "dropshit" don't help...nor does commenting each line in the code with the same info you get in the code line itself. And the number of regions is pretty silly - if you need a region inside your method, the code in the region should probably be in a method...
15 Aug 2011 by Paul_Williams
The difference between ListBox and CheckedListBox DataBinding.
11 May 2012 by VJ Reddy
The following code can be used in the Click event of a Button, to find if any of the items in CheckedListBox is available in the ListBox. If available then the boolean flag notFound is set to false.bool notFound = true;checkedListBox1.Items.Cast().Select (s => { if...
10 Jul 2013 by Pheonyx
I found my Issue, My ViewModel was inheriting from a base class that implemented INotifyPropertyChanged, however I had to declare my viewModel as such:internal class myVM: myBaseVM, INotifyPropertyChangedand ensure the correct references were in place else it failed to trigger the...
16 Jan 2014 by CBadger
Try thisbool bHScroll = (m_List.GetStyle()&WS_HSCROLL)!=0;bool bVScroll = (m_List.GetStyle()&WS_VSCROLL)!=0;// if not answer look at source :-)source[+]
2 Feb 2014 by Karthik_Mahalingam
Try this for (int indexCounter = 0; indexCounter
15 Feb 2011 by Nish Nishant
Handle the ListBox's SelectedIndexChanged event and update the PictureBox according to the new selection.
27 Jul 2011 by saurabhd13
Hi Friends Hope you all are doing good. I have few questions about WPF List BOX Some Background:We are trying to build a scheduling control like outlook with some custom functionality.I have already gone through the similar post in Code Project but we tend to take slightly...
19 Dec 2011 by KiranBabu M
Hello,I have some 1000 .jpg images in a folder, Now i want to display these images with image number in a listbox.For this i have taken a collection of images and set as listbox item source. but the application is very slow as it is loading all the images at a time in to listbox.so i...
17 Mar 2012 by ProEnggSoft
The FindString method of ListBox control returns the index of string in the items of the ListBox as shown below:int orangeIndex = listBox1.FindString("Orange");int appleIndex = listBox1.FindString("Apple");
30 Apr 2012 by Shahin Khorshidnia
HelloUse this: ...
2 May 2012 by Maciej Los
Sandeep Mewara was trying to tell you to use selecteditem object, not ListBox1.SelectedItems(LBitmCounter). In my example i replaced it with oItemFor Each oItem As [Object] In ListBox1.SelectedItems If oItem.ToString = "Text 1" Then Action 1 ElseIf oItem.ToString = "Text 2"...
13 May 2013 by Aydin Homay
Hi againIt is really easy just you should register SelectedIndexChanged event for listbox2 and make your query follow of :void listBox1_SelectedIndexChanged(object sender, EventArgs e) { string bindingQuerylistBox2 = string.Empty; bindingQuerylistBox2 = "select *...
13 May 2013 by Aydin Homay
private void Form2_Load(object sender, EventArgs e) { SqlConnection cs = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=details;User ID=sa;Password=P@ssw0rd"); SqlCommand cmd = new SqlCommand(); cmd.Connection = cs; ...
14 Jun 2013 by JNDIONYSIM
Check this link and scroll to Forms over Data Video Series section....http://msdn.microsoft.com/en-US/vstudio/bb466226.aspx[^]You will found a lot of interesting information ... You can do what you are asking for in visual studio 2012 with out writing a single line of code :)You can...
22 Aug 2013 by Richard MacCutchan
Use the CListBox::SetCurSel[^] function to clear the selection, probably in the OnKillFocus[^] override.
23 Mar 2014 by BillWoodruff
After playing with the CheckedListBox a while, I am convinced you will find it much easier to implement this using two ListBoxes. The ListBox offers you built-in sorting by setting its 'Sorted Property to 'true.If you still really wish to use a CheckedListBox, hopefully this code will give...
12 Jun 2015 by CHill60
Try thisstring input = "9000384454|130945522842|13098575900|917379563772|919014742532|99484575475";var items = input.Split(new []{'|'}, StringSplitOptions.RemoveEmptyEntries);listBox1.DataSource = items;
26 Dec 2016 by Philippe Mori
Well, that code look a lot more like school project code than professional code! Here are my suggestions:#1 Follows the nomenclature of the language/framework. In .NET, Pascal casing is normally used for classes and functions names (ClassName, FunctionName) . Variables should use camel...
23 Feb 2017 by Karthik_Mahalingam
try this, corrected code and custom search. private void btAdd_Click(object sender, EventArgs e) { string nameFamily = tbName.Text + " | " + tbFamily.Text; listnames.Items.Add(nameFamily + " | " + tbTell.Text); } private void...
7 Feb 2018 by Maciej Los
If you would like to split listbox item into parts, use ListBox.SelectedIndexChanged Event (System.Windows.Forms)[^] Then, inside that event, paste below code: Dim curItem As String = ListBox1.SelectedItem.ToString() Dim parts As String() = curItem.Split(New String(){","},...
14 Feb 2019 by OriginalGriff
You could remove the event from the handlers list and add it back at the end: Add and remove event handlers dynamically in VB.NET[^] That effectively "disables" it while it's being filled.
2 Oct 2019 by Maciej Los
Wel... Start here: Ready-to-use serial port enumeration list box[^] For further details, please see: SerialPort.GetPortNames Method (System.IO.Ports) | Microsoft Docs[^] [EDIT] There's no guarantee that SerialPort.GetPortNames method will return the names of ports. But, there's work-around....
12 Mar 2020 by phil.o
You could give Form2 a constructor accepting an enumeration of integers as parameter, which you would use to populate the second listbox: public Form2() { InitializeComponent(); } public Form2(IEnumerable values) : this() { ...
12 Mar 2020 by Maciej Los
In addition to @phil.o solution, i'd suggest to read these very interesting tips/articles: Transferring information between two forms, Part 1: Parent to Child[^] Transferring information between two forms, Part 2: Child to Parent[^] Transferring...
4 Aug 2020 by TheRealSteveJudge
First of all you must cast "sender" which is just an object to "ComboBox". Then you must get "SelectedValue". Finally you must get the files that are in the selected directory and use it as data source for the ListBox. private void...
7 Aug 2020 by Richard Deeming
Something like this should work: var fileNames = directoryInfo.EnumerateFiles() .Select(f => f.Name) .ToLookup(f => Path.GetFileNameWithoutExtension(f).LastOrDefault()); listBox1.DataSource = fileNames['a']; listBox2.DataSource =...
22 Nov 2020 by PIEBALDconsult
Define a class, with the two values, a ToString for displaying them together, and a compare method which sorts by last then first.
29 Mar 2021 by Maciej Los
Try this: Dim clipNumbers = clipboarddata.Split(New String(){Microsoft.VisualBasic.vbNewLine}, StringSplitOptions.RemoveEmptyEntries) _ .Select(Function(x) New SortedNumbers With {.RandomNumber =Math.Abs(Convert.ToInt32(x))}) _...
31 Jan 2022 by OriginalGriff
The problem is that you can't do it like that: you are providing string based data, so the comparison is always going to be string based - and that means that the result of the entire comparison is based on the first different character in the...
24 May 2020 by OriginalGriff
It's because the font that the ListBox is using to display the strings is a proportional font: not all the characters are the same width. For example, "i" is much narrower than "W", and "." is really narrow while "#" is a lot wider. Change the...
10 May 2010 by William Winner
I'm a little bit confused with what you are asking, but here is what it seems to me.You want a ListBox to show just a name. You want that when the ListBox Item is clicked, you can pull out from that item where the video file is. Is that correct?If so, there are a couple of options...
9 Jul 2010 by #realJSOP
I wrote an article that customizes the drawing in a ListBox. Anagrams - A Word Game in C#[^]The following is an excerpt of the appropriate section of the article:The Word ListI wanted a way to show the user what he'd typed, so I decided on a list box. As the program validates...
9 Jul 2010 by DaveyM69
This code colors the item's background based on index - ammend to work on a property of the item at that index.(Form [FormMain] with a ListBox added called listBox)using System.Drawing;using System.Windows.Forms;namespace CP.QA.WinForms{ public partial class FormMain : Form ...
30 Dec 2010 by William Winner
What you would want to do is hook the textbox's TextChanged event. Because you've databound that textbox, the listbox has no knowledge of the textbox, so that's where you would have to start.So, in that event, you would just draw a box around the textbox with the color that is in the...
17 Jan 2011 by Manfred Rudolf Bihy
A ListBox has display strings those are the ones you see in the GUI and associated with each of these display strings is a value. So the DisplayMember of ListControl gives you the string as you see it in your GUI and the ValueMember property of ListControl (ListBox is derived from ListControl)...
24 Jan 2011 by Corinna John
The listbox stores only plain text, so you have to store the relevant information about your records in another list or in a dataset. As long as your listbox is not sorted (that means, listbox and objects list are in same order) you can do something like that:for(int i=0; i
21 Jan 2011 by Hiren solanki
ListBox lst = new ListBox(); lst.Items.Add(new ListItem("rupa")); lst.Items.Add(new ListItem("anitha")); lst.Items.Add(new ListItem("latha")); lst.Items.Add(new ListItem("rani"));That is what you looking for ?Ok now as manfred suggested I can revise my...
21 Jan 2011 by Sergey Alexandrovich Kryukov
Formally, there are correct answers already.I would add advice a minor improvement to all the presented codes:string[] items = source.Split( new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);It allows for more relaxed human-readable requirements for the format...
23 Jan 2011 by Henry Minute
ListView has the TopItem property that you could use.
10 Feb 2011 by #realJSOP
Try this:ta = cbxGenre.SelectedText;Have you considered using the debugger?
16 Feb 2011 by OriginalGriff
All you have to do is set the PictureBox.Image property:if (myPicture.Image != null) { myPicture.Image.Dispose(); }myPicture.Image = Image.FromFile(@"F:\Temp\MyImage.jpg");The dispose just tidies up after yourself!You can use any image source you have: it could be a Bitmap...
16 Feb 2011 by Espen Harlinn
This may be of interest:Extending the ListBox to show more complex items[^] - provides a listbox that allows you to display an image to the right of the text.RegardsEspen Harlinn
8 Mar 2011 by Tarun.K.S
From my understanding, When you bind an Image in XAML, it must be of type BitmapImage. So you can change the type of Image in your MyItemType class to BitmapImage instead of byte[]. You don't have to convert it into byte.In short, this is what you have to do.public class...
29 Mar 2011 by Henry Minute
For WindowsForms take a look at this thread[^].
31 Mar 2011 by BobJanova
If you inherit from UserControl you need to do everything yourself, including managing the list of items that are in the list box. For example, here is my control to solve a similar problem.
20 Apr 2011 by Maciej Los
1) Only for the first time (i=0) you can add parameter! For the next loop you must change it!or...2) Build query in run-time in this way:sSQL = "INSERT INTO Tracks (TrackTitle, TrackSeqNum) " & vbCrLf & _"VALUES( '" & ListBox3.Items(i) & "', '" & ListBox1.Items(i)"')"Then you need to...
17 Jun 2011 by trirnd
Next example shows grouped items when your mouse is over the group, hope this is what you requested:
25 Jul 2011 by UJimbo
The List was a change in the right direction. Take a look at this code for export and Import:private void ExportXML(){ try { System.Collections.Generic.List theList = new System.Collections.Generic.List(); XmlSerializer serializer = new...
10 Aug 2011 by Mahendra.p25
set AutoPostBack="true"
12 Aug 2011 by KiranBabu M
Hi,can any one give example how to clear images displayed in a listbox.I have listbox and two buttons on the form.when i click on first button(to select path of the images folder). and second button to display images in the listbox. for this i have talen a ImagesList.And all the images...
21 Aug 2011 by H. S. Masud
I'm developing an opensource application named Media Assistant[^]. I used a ListBox to show the library. ItemsSource is bound to a list of LibraryItem. Here is the XALM. ItemsSource="{Binding DataSource.OrderedLibraryItems}" ...
24 Aug 2011 by H. S. Masud
I found the reason behind this, so the solution. I used a DockPanel to layout my UI. I put my status bar at the bottom, the ListBox on the Left and other items are on middle and top. There is a TextBlock in my StatusBar which has width and Height set to Auto. So, when I changed text of my...
5 Oct 2011 by Espen Harlinn
Take a look at:GridView Multiple Filter AJAX Control[^]andMultiDropDown v2: A multiple selection Dropdown control for ASP.NET[^]Those two articles covers most of what you need to know...Best regardsEspen Harlinn
26 Oct 2011 by Orcun Iyigun
Do you know the magic tool called "Debugger" :) use it and will be amaze by the results.. use the Debugger in your button click code and see where the value that you are assigning is null. that's why it is throwing that error.
9 Nov 2011 by KiranBabu M
Hi all,i want to perform the drag and drop for items in a list box. list box items source is the collection List.i have two list boxes. listbox1 contains all the items. i will drag and drop the selected items from list box1 to list box2(the items should be copied to listbox2). now in...
6 Dec 2011 by S V Saichandra
Asp.Net Listbox and Tree View Code Updated:UI:
9 Dec 2011 by Abhinav S
Obtain the value from the textbox and then use the FindString method inside a Listbox. See here[^].
19 Dec 2011 by Sergey Alexandrovich Kryukov
Showing one image at a time is usually fast enough, if the image is of the screen size or even more, but 1000 or so… no wonder it's too slow.You can try few different things. First, you can put only small thumbnail-size images in your list box. I hope you understand: not the images...
19 Dec 2011 by Amir Mahfoozi
It seems that you need virtualization in wpf , so have look at these pages :WPF: Data...
8 Mar 2012 by Muthu Nadar
Dude... I also came through certain situation.But the only change in my case is, it was checklistbox.If I am not wrong, you must facing problem like,On selection of list value you need the current selectedvalue,but you must be getting the first selected value on every selection...
12 Apr 2012 by Wes Aday
You need to call reader.Read() before trying to access the data. In your example you are calling it after. Change your "do" loop to a "while" should fix it.while(reader.Read()){ tempVal = reader[0].ToString(); }
20 Apr 2012 by Umer Aziz Malik
Hello cebe_noyan,I did not get you question properly but here is my interpretation of your problem:You want to copy files specified (source files)in a listbox to a specific directory(target location). I take that the path of the source files if given.Here's the solution i...
3 Jun 2012 by vivek.bagdai
For File browser you need two thing1. Directory path (Directory which user selects)2. List of all file.for 1. Requirement you can use FileBrowser,and for 2.you have to add list box and load all file list in the below code will help//Here "c:\user\public\picture" is Directory...
8 Jul 2012 by Prasad_Kulkarni
Does google broken at your side?Multiselect in listbox search on Google[^] gave me About 135,000 results (0.13 seconds). Visit it sometimes.You can try MSDN also:ListBox Class[^] for detailed description with some examples.Or else search on CodeProject QA forums[^] for similar...
14 Aug 2012 by Zoltán Zörgő
Wait! You have confused everything! This has nothing to do with VisualStudio. And either you use WPF or WindowsForms control. PresentationFramework.dll is WPF, the link is for the WindowsForms control.To allow user to select all elements in wpf listbox look here:...
28 Oct 2012 by Cagri Kaynar
try this code lbItemsList.BeginUpdate(); lbItemsList.DataSource = null; lbItemsList.DataSource = shoppingBasket.OrderItems; lbItemsList.EndUpdate();
8 Dec 2012 by Crispanvarro
I can clear all the text boxes when i press reset button ,ie, txtName.text = "".. i can clear the combo boxes in the same way,but how do i reset the radiobuttons,checkboxes and listbox contents that have been selected.
8 Dec 2012 by Krunal Rohit
Its C# code, I've solved yesterday similar kinda question :private void button1_Click_1(object sender, EventArgs e) { List t = new List(); t.Add(textBox1); t.Add(textBox2); t.Add(textBox3); ...
16 Dec 2012 by Espen Harlinn
"Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead."That sounds like a good advice.Add your items to an ObservableCollection
18 Feb 2013 by Marco Bertschi
You can use a list box with pictures [^] at the left hand side for the menu and when the selected index on the list box changes you can load another user control on the area on the right hand side.Use the OnSelectedItemChanged - Event[^] of the list view to find out when the listbox' index...
10 Apr 2013 by Sergey Alexandrovich Kryukov
I don't know how to talk with you (please see the comments to Solution 1). You probably need to know what are the involved directories. Please see my past comprehensive answers:How to find my programs directory ( executable directory),How to find my programs directory (current directory,...
10 May 2013 by Aydin Homay
Hi NirmalPlease change your binding solution, your solution is not good solution so please review follow of links and use list box DataSource property for this purpose, if you have a any question after review these links please take a comment for me ;)...
6 Jun 2013 by rmerca
This is an alternative for "Checkbox List With Filtering jQuery Widget"
27 Jun 2013 by Jason Gleim
I'm going to expand my comment...ItemSource is meant to be bound to an object that supports property change notification. What you should do is implement INotifyPropertyChanged on your class (I'm assuming the code-behind for that page) then add a property for each ItemSource:public...
27 Jun 2013 by kpolecastro
Imagine the items in triplicate for the different listboxes Source="{Binding Source={x:Static Application.Current}, Path=CurrentList}" x:Key="CurrentList" /> > ...
28 Jun 2013 by OriginalGriff
Whenever you handle the SelectionChanged event, you have to check if there are any selected items - because if there aren't then you will get a null reference exception when you try to use the SelectedItem property. And you get the event when you clear the list!Just check at the top of your...
27 Jun 2013 by kpolecastro
To anyone that can help or show me a better way. I have tried to do this with an observable collection, a list based on a custom class, global/non-global collections, using the listbox's itemssource, synclocking, and finally emptying and manually entering in items.It tends to work fine, but...
27 Jun 2013 by Pheonyx
I've seen similar issues, and managed to fix them by re-working the code.The first change I would make would be with these:Try For I = Me.ParentListbox.Items.Count - 1 To 0 Step -1 Me.ParentListbox.Items.RemoveAt(I) NextCatchEnd TryTry For I =...
11 Jul 2013 by minalmt
Hi,I am looking for some help implementing two way drag and drop functionality between ListBox and DataGrid column in WPF. i have searched through the net and managed to grab drag-drop samples but they don't fulfill my needs, plus most of them are having some missing codes. My datagrid...
25 Jul 2013 by Richard MacCutchan
You could start by looking at Creating Custom Controls[^], by our glorious leader.
25 Aug 2013 by BillWoodruff
First, to the issue of other Controls "showing through:" unless you are using a UserControl that implements transparency (and getting a Windows Form UserControl to have any useful transparency is a dubious proposition), the only way any other control can "show through," is if it is placed on top...
5 Sep 2013 by Mike Meinz
Successful Example - Revised 5 Sep 2013 10:57 EDT to include RemoveAtThe following code works. I tested using Visual Studio 2012 on a Windows 8 PC. By using the Visual Studio Interactive Debugger, I determined that all visible rows in the ListBox are refreshed when a new row is added and...
11 Oct 2013 by ASP.NET Community
The ListBox control is used to create a list control that allows single or multiple item selection. Use the Rows property to specify the height of
19 Jan 2014 by olid4
When there's no better way, I think this is the best way to solve the problem:if(rectListBox.Height() > GetLBox().GetCount() * GetLBox().GetItemHeight(0))There may be some problems with borders and stuff like that. But IMHO this should work appropriate in most cases.
2 Feb 2014 by Praveen_P
Hope this will meet your requirementforeach (ListItem lst in test_names.Items) { if (lst.Selected) { string selectedValue = lst.Value; string patient_id = Request.QueryString["id"]; SqlConnection cnm = new...
25 Feb 2014 by Maciej Los
You should forget about DAO. Use ADO.net[^]!How To Use ADO.NET to Retrieve and Modify Records in an Excel Workbook With Visual Basic .NET[^]Accessing Microsoft Office Data from .NET Applications[^]Using ADO.NET to work with Excel files[^]USING ADO AND ADO.NET WITH EXCEL: Resources and...
5 Jul 2019 by Ahmad_kelany
hi everyone,i searched for changing ListBoxItem back color and persisting this selection color even if the control lost focusi found the solution like this :
4 May 2014 by Peter Leow
Study this example and adapt it to your need:the aspx page:
3 Jun 2014 by Sergey Alexandrovich Kryukov
Please see my comment to the question, and also this:http://msdn.microsoft.com/en-us/library/c1sez4sc%28v=vs.110%29.aspx[^],http://msdn.microsoft.com/en-us/library/07wt70x2%28v=vs.110%29.aspx[^];alternatively, to request recursive...
11 Oct 2014 by BillWoodruff
'Utils is a Class, but in your code you never create an instance of that class.Like this: Utils currentUtils = new Utils();Once you have an instance of the Class, you can access the Public ListstringListLike this (in your Main Form):foreach(string receivableItem in...
8 Oct 2015 by Ramza360
First it makes a copy of the text in the DataTextBox.Text property.string data = DataTextBox.TextThen instantiates a new List, with the data returned by the Split call.List gradeString = new List(data.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));The...