Windows forms combobox with checkboxes

Combobox with checkbox in winforms

I am trying to look for a simple way to design a winform with a combobox that has checkbox values in it to select multiple values. But there are no free samples I could find.

If anybody has a good link for a sample which does not require a license. Please let me know.

I am not looking for controls like telerik and infragistics.

3 Answers 3

Maybe this example can help you.

It sounds like what you really want is a checked listbox control or maybe even just a listbox. These controls do multi-select in a way that is more standard for Windows.

If you really need a combo box with checkboxes in it, here’s an article on code project I used once.

My suggestion, if space is an issue as @rmc00 has eluded to, place a button at the end of a readonly Textbox with perhaps an elipse (. ) or down arrow (same as combobox) as the text of the button and when clicked or MouseDown make visible and position a CheckBoxList or open a popup dialog with a CheckBoxList this way you can either prepopulate at design time or pass a DataTable as a parameter/property to your control/form so it is databound at runtime. You can always place your control or write code to position the control/form exactly below your TextBox in the MouseDown/Click event. On check change update your textbox with a comma separated list (or go fancy and say if more than 3 items the text box can have the list stored in the Tag and the TextBox Text can have the count of items checked). Finally on LostFocus hide the Control (or Form), and further if you want to get fancy make the exception to not hide when the ActiveControl is the Button that way you can toggle the visibility of consecutive button presses.

Читайте также:  Как восстановить панель уведомлений windows 10

WPF ComboBox with CheckBoxes display info about checked items?

Im trying to make a ComboBox that have checkboxes as items and based on what is checked display different things when the combobox is «closed».

The look Im trying achieve can be seen in the image.

Ideally I dont want the user to be able to select the text in the top ( in the image).

Is there a simple solution to this? I’ve seen solutions where one can display more information when all the items are shown by using DataTriggers to hide different nested controls, but that is not really what Im looking for.

3 Answers 3

Here is a way to achieve most of what you want using a ComboBox , except that the text can still be selected (using custom text only works when IsEditable is true). It is not editable though because of IsReadOnly=»true» .

View

Viewmodel

If the selectable text is an issue, you may want to create a custom ComboBox control template (default example here). Alternatively, you could use something else instead of a ComboBox , and make it look like a ComboBox .

Screenshot of example:

@Xaviers answer works 99% of the way. However the user is able to accidently select a checkbox and then the ToString() of the checkbox is shown as the selected text. This can happen quite alot actually. I havent yet worked out why this happens, but I’ve found a way to prevent this.

Create a bool property that binds to the DropDownOpen property of the combobox and when the DropDownOpen has changed to false it means that the DropDown has just been closed and you might be facing the above problem. So here you just raise the propertychanged event for the viewmodel and pass the property bound to the Text property of the combobox.

Using a combination of the @Erik83 and @Xavier solution I still had the problem that selecting a ComboBoxItem in a location right from the CheckBox text closes the ComboBox-DropDown and shows the ToString() value of the ComboBoxItem as the CheckBox is not stretched to DropDown-Width. I solved it by adding

to the CheckBox and adding the ItemContainerStyle:

Not the answer you’re looking for? Browse other questions tagged c# wpf combobox or ask your own question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Читайте также:  Накопительное обновление для windows 10 version 20h2 kb4598242

How to add check box inside combobox in c#

I want to add check box inside comboBox in C#. My purpose is that the user can select multiple values from one ComboBox ( Check all and Uncheck all ).

3 Answers 3

You have to extend the ComboBox control by providing your own rendering strategy, and «manually» adding a CheckBox.

Theses open source project are ready to use :

It is a wrong usage of a ComboBox control, because the user has no possibility to see his choices. For multiple selection, I recommend you to consider this CheckedListBox control:

There is an ASP.NET open source control at http://dropdowncheckboxes.codeplex.com/ that I’ve used and been very happy with. There is also a WinForms open source control at http://www.codeproject.com/KB/combobox/extending_combobox.aspx that doesn’t look quite as strong but maybe somebody could combine the best of both. If well implemented this is really a great addition to your toolkit. The above 2 implementations show all of the items selected and give you a number of related checkboxes in a reduced area and with excellent grouping. My addition to the ASP.NET version was to allow a list of checked files to use just file names instead of full paths if this gets too long. See above link for full code. Below is just my addition which is called instead of UpdateSelection in your postback handler:

Not the answer you’re looking for? Browse other questions tagged c# combobox checkbox or ask your own question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Combobox с элементами CheckBox

Реализация ComboBox в ячейке DataGridView с элементами CheckBox и RadioButton
Добрый день. Помогите, пожалуйста, разобраться в решении следующей задачи. Таблица DataGridView.

Не справляюсь с checkBox, listBox и comboBox
Вообще в программе есть: 1) comboBox1: выпадающий список групп «10331-С72» и «10332-С72». 2) Два.

Как добавить CheckBox в ComboBox
Здравствуйте, как можно добавить CheckBox в ComboBox, чтобы при раскрытии списка ComboBox внутри.

Выключатели CheckBox — запрещения изменений в ComboBox
выключатели CheckBox ( не использовать свойства типа Visible и Enable) запрещения изменений в.

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

Вытащить из ComboBox значения всех CheckBox
Здравствуйте. Есть комбобокс, внутри чекбоксы. Надо значения чекбоксов перенсти в другой.

Читайте также:  Running windows from mac

Можно ли сделать удаление из combobox по отмеченным checkbox?
В combox1 есть список слов(5 слов),возможно ли сделать так,чтобы при нажатии «Удалить» в.

DataGridView с элементами ComboBox
Помогите. Очень нужно. Необходимо создать datagridview с НЕСКОЛЬКИМИ элементами combobox. Наличие.

Заполнение элементами combobox
На каком этапе будет правильнее заполнять combobox элементами из БД? На этапе открытия формы.

Автоматическое удаление текста в comboBox при отмеченном CheckBox
Помогите пожалуйста! как сделать, чтобы если comboBox отмечен галочкой, то запись удаляется.

Практическое руководство. Добавление и удаление элементов, отображаемых в элементах управления ComboBox, ListBox и CheckedListBox в Windows Forms How to: Add and Remove Items from a Windows Forms ComboBox, ListBox, or CheckedListBox Control

Элементы могут быть добавлены в Windows Forms поле со списком, списком или списком флажков различными способами, поскольку эти элементы управления могут быть привязаны к различным источникам данных. Items can be added to a Windows Forms combo box, list box, or checked list box in a variety of ways, because these controls can be bound to a variety of data sources. Однако в этом разделе демонстрируется простейший метод и не требуется привязка данных. However, this topic demonstrates the simplest method and requires no data binding. Отображаемые элементы обычно являются строками. Однако можно использовать любой объект. The items displayed are usually strings; however, any object can be used. Текст, отображаемый в элементе управления, является значением, возвращаемым ToString методом объекта. The text that is displayed in the control is the value returned by the object’s ToString method.

Добавление элементов To add items

Добавьте строку или объект в список с помощью Add метода ObjectCollection класса. Add the string or object to the list by using the Add method of the ObjectCollection class. Ссылка на коллекцию осуществляется с помощью Items Свойства: The collection is referenced using the Items property:

Вставьте строку или объект в нужную точку списка с помощью Insert метода: Insert the string or object at the desired point in the list with the Insert method:

Назначьте весь массив Items коллекции: Assign an entire array to the Items collection:

Удаление элемента To remove an item

Вызовите Remove метод или, RemoveAt чтобы удалить элементы. Call the Remove or RemoveAt method to delete items.

Remove содержит один аргумент, указывающий удаляемый элемент. RemoveAt Remove has one argument that specifies the item to remove. RemoveAt Удаляет элемент с указанным номером индекса. removes the item with the specified index number.

Удаление всех элементов To remove all items

Вызовите Clear метод, чтобы удалить все элементы из коллекции: Call the Clear method to remove all items from the collection:

Оцените статью