I have a form in C# that uses a ComboBox
.
How do I prevent a user from manually inputting text in the ComboBox
in C#?
this.comboBoxType.Font = new System.Drawing.Font("Arial", 15.75F);
this.comboBoxType.FormattingEnabled = true;
this.comboBoxType.Items.AddRange(new object[] {
"a",
"b",
"c"});
this.comboBoxType.Location = new System.Drawing.Point(742, 364);
this.comboBoxType.Name = "comboBoxType";
this.comboBoxType.Size = new System.Drawing.Size(89, 32);
this.comboBoxType.TabIndex = 57;
I want A B C to be the only options.
dur
15.8k25 gold badges81 silver badges125 bronze badges
asked Mar 10, 2012 at 17:07
1
Just set your combo as a DropDownList:
this.comboBoxType.DropDownStyle = ComboBoxStyle.DropDownList;
answered Mar 10, 2012 at 17:10
ReinaldoReinaldo
4,5763 gold badges24 silver badges24 bronze badges
2
I believe you want to set the DropDownStyle to DropDownList.
this.comboBoxType.DropDownStyle =
System.Windows.Forms.ComboBoxStyle.DropDownList;
Alternatively, you can do this from the WinForms designer by selecting the control, going to the Properties Window, and changing the «DropDownStyle» property to «DropDownList».
answered Mar 10, 2012 at 17:09
Justin PihonyJustin Pihony
66.2k18 gold badges147 silver badges180 bronze badges
You can suppress handling of the key press by adding e.Handled = true
to the control’s KeyPress event:
private void Combo1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
answered Nov 26, 2012 at 8:27
sherin_sherin_
3525 silver badges15 bronze badges
2
I like to keep the ability to manually insert stuff, but limit the selected items to what’s in the list.
I’d add this event to the ComboBox. As long as you get the SelectedItem and not the Text, you get the correct predefined items; a, b and c.
private void cbx_LostFocus(object sender, EventArgs e)
{
if (!(sender is ComboBox cbx)) return;
int i;
cbx.SelectedIndex = (i = cbx.FindString(cbx.Text)) >= 0 ? i : 0;
}
answered Jul 17, 2018 at 12:40
TatesTates
791 silver badge1 bronze badge
Why use ComboBox then?
C# has a control called Listbox. Technically a ComboBox’s difference on a Listbox is that a ComboBox can receive input, so if it’s not the control you need then i suggest you use ListBox
Listbox Consumption guide here: C# ListBox
answered Mar 9, 2015 at 2:16
DevEstacionDevEstacion
1,9571 gold badge14 silver badges28 bronze badges
Morchant |
|
1 |
|
26.09.2011, 17:46. Показов 99796. Ответов 31
Как сделать, чтобы варианты можно было выбирать только из предложенных, без возможности редактирования? |
kolorotur 17366 / 12773 / 3343 Регистрация: 17.09.2011 Сообщений: 21,059 |
||||
26.09.2011, 17:48 |
2 |
|||
Сообщение было отмечено как решение Решение
19 |
Morchant |
|
26.09.2011, 18:18 |
3 |
Благодарю |
15 / 15 / 7 Регистрация: 21.08.2013 Сообщений: 115 |
|
05.05.2014, 13:02 |
4 |
Однако, если это свойсво повесить в свойствай КомбоБокс-а — то вываливается ошибка.
1 |
17366 / 12773 / 3343 Регистрация: 17.09.2011 Сообщений: 21,059 |
|
05.05.2014, 13:49 |
5 |
вываливается ошибка. Какая?
0 |
insite2012 5495 / 4264 / 1212 Регистрация: 12.10.2013 Сообщений: 12,270 Записей в блоге: 2 |
||||
05.05.2014, 20:21 |
6 |
|||
3 |
2149 / 1286 / 516 Регистрация: 04.03.2014 Сообщений: 4,092 |
|
05.05.2014, 21:22 |
7 |
insite2012, зачем велосипед ? и возможная ошибка пустого значения ? если — «DropDownStyle »
0 |
15 / 15 / 7 Регистрация: 21.08.2013 Сообщений: 115 |
|
06.05.2014, 06:16 |
8 |
Какая? Во какая… Миниатюры
0 |
17366 / 12773 / 3343 Регистрация: 17.09.2011 Сообщений: 21,059 |
|
06.05.2014, 14:13 |
9 |
Во какая… Какое отношение она имеет к запрету ввода собственного значения в выпадающий список?
0 |
2149 / 1286 / 516 Регистрация: 04.03.2014 Сообщений: 4,092 |
|
06.05.2014, 14:22 |
10 |
mvs87, а что ты хочешь этим получить?
0 |
mvs87 15 / 15 / 7 Регистрация: 21.08.2013 Сообщений: 115 |
||||
06.05.2014, 15:00 |
11 |
|||
Какое отношение она имеет к запрету ввода собственного значения в выпадающий список? Где то натыкался что так можно. Проверил. Не вариант.
mvs87, а что ты хочешь этим получить? Хочу получить тоже самое, если прописать
только в свойствах стаивть.
0 |
2149 / 1286 / 516 Регистрация: 04.03.2014 Сообщений: 4,092 |
|
06.05.2014, 15:08 |
12 |
mvs87, а в чем проблема если так и прописать?
0 |
15 / 15 / 7 Регистрация: 21.08.2013 Сообщений: 115 |
|
07.05.2014, 06:03 |
13 |
mvs87, а в чем проблема если так и прописать? В раздувании кода.
0 |
17366 / 12773 / 3343 Регистрация: 17.09.2011 Сообщений: 21,059 |
|
07.05.2014, 11:22 |
14 |
Где то натыкался что так можно. Проверил. Не вариант. У вас явно ошибка в коде — использование списка происходит еще до того, как свойство будет установлено.
0 |
Shah88 0 / 0 / 0 Регистрация: 10.11.2014 Сообщений: 1 |
||||
07.02.2015, 00:32 |
15 |
|||
Помогло! Спасибо)
0 |
0 / 0 / 0 Регистрация: 08.10.2017 Сообщений: 5 |
|
25.11.2017, 20:53 |
16 |
У меня такая же проблема. Только вот код, который представлен выше, никак не помог. Он просто игнорит и все равно допускает ввод пользователем комбоксы. Может не туда вставил код? у меня комбоксы играют роль критерии поиска. Можно, в свойствах, как то запретить ? или только кодом?
0 |
3477 / 2482 / 1172 Регистрация: 14.08.2016 Сообщений: 8,180 |
|
26.11.2017, 00:04 |
17 |
можно в свойствах, третий сверху
1 |
0 / 0 / 0 Регистрация: 24.11.2017 Сообщений: 48 |
|
13.04.2018, 19:31 |
18 |
здравствуйте, не могли бы вы,если не сложно, поподробней объяснить, как работает эта строка?
comboBox1.KeyPress += (sender, e) => e.Handled = true; в частности, почему «+=(sender, e) =>»? что оно делает?
0 |
kolorotur 17366 / 12773 / 3343 Регистрация: 17.09.2011 Сообщений: 21,059 |
||||||||
14.04.2018, 11:04 |
19 |
|||||||
что оно делает? Подписывает на событие анонимный метод.
Что в свою очередь эквивалентно такой записи:
1 |
387 / 265 / 117 Регистрация: 09.07.2021 Сообщений: 965 |
|
23.12.2021, 18:04 |
20 |
0 |
I have a form in C# that uses a ComboBox
.
How do I prevent a user from manually inputting text in the ComboBox
in C#?
this.comboBoxType.Font = new System.Drawing.Font("Arial", 15.75F);
this.comboBoxType.FormattingEnabled = true;
this.comboBoxType.Items.AddRange(new object[] {
"a",
"b",
"c"});
this.comboBoxType.Location = new System.Drawing.Point(742, 364);
this.comboBoxType.Name = "comboBoxType";
this.comboBoxType.Size = new System.Drawing.Size(89, 32);
this.comboBoxType.TabIndex = 57;
I want A B C to be the only options.
dur
15.8k25 gold badges81 silver badges125 bronze badges
asked Mar 10, 2012 at 17:07
1
Just set your combo as a DropDownList:
this.comboBoxType.DropDownStyle = ComboBoxStyle.DropDownList;
answered Mar 10, 2012 at 17:10
ReinaldoReinaldo
4,5763 gold badges24 silver badges24 bronze badges
2
I believe you want to set the DropDownStyle to DropDownList.
this.comboBoxType.DropDownStyle =
System.Windows.Forms.ComboBoxStyle.DropDownList;
Alternatively, you can do this from the WinForms designer by selecting the control, going to the Properties Window, and changing the «DropDownStyle» property to «DropDownList».
answered Mar 10, 2012 at 17:09
Justin PihonyJustin Pihony
66.2k18 gold badges147 silver badges180 bronze badges
You can suppress handling of the key press by adding e.Handled = true
to the control’s KeyPress event:
private void Combo1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
answered Nov 26, 2012 at 8:27
sherin_sherin_
3525 silver badges15 bronze badges
2
I like to keep the ability to manually insert stuff, but limit the selected items to what’s in the list.
I’d add this event to the ComboBox. As long as you get the SelectedItem and not the Text, you get the correct predefined items; a, b and c.
private void cbx_LostFocus(object sender, EventArgs e)
{
if (!(sender is ComboBox cbx)) return;
int i;
cbx.SelectedIndex = (i = cbx.FindString(cbx.Text)) >= 0 ? i : 0;
}
answered Jul 17, 2018 at 12:40
TatesTates
791 silver badge1 bronze badge
Why use ComboBox then?
C# has a control called Listbox. Technically a ComboBox’s difference on a Listbox is that a ComboBox can receive input, so if it’s not the control you need then i suggest you use ListBox
Listbox Consumption guide here: C# ListBox
answered Mar 9, 2015 at 2:16
DevEstacionDevEstacion
1,9571 gold badge14 silver badges28 bronze badges
- Remove From My Forums
-
Question
-
hello,i have one combobox «gender field » with 2 choices (Male /Femelle)
i try to disable write writing in this field ,i need just chosse F or M
the problem is that field editable,when i excute program !!
Answers
-
Go to Form Designer, select the combobox, then set its “DropDownStyle” property to “DropDownList”. Can be done programmatically too.
-
Proposed as answer by
Thursday, May 5, 2016 12:35 AM
-
Marked as answer by
DotNet Wang
Monday, May 16, 2016 12:30 PM
-
Proposed as answer by
-
Hi foxnight,
You could also use in backend code to make your combobox read only. Hope this helps you. See below:
using System; using System.Windows.Forms; namespace WindowsFormsApplication12 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; } } }
Thanks,
Sabah Shariq
-
Marked as answer by
DotNet Wang
Monday, May 16, 2016 12:30 PM
-
Marked as answer by
I want to have a «select-only» ComboBox
that provides a list of items for the user to select from. Typing should be disabled in the text portion of the ComboBox
control.
My initial googling of this turned up an overly complex, misguided suggestion to capture the KeyPress
event.
asked Sep 17, 2008 at 17:37
Cory EngebretsonCory Engebretson
7,6634 gold badges22 silver badges17 bronze badges
To make the text portion of a ComboBox non-editable, set the DropDownStyle property to «DropDownList». The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this:
stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
Link to the documentation for the ComboBox DropDownStyle property on MSDN.
Omar
16.4k10 gold badges48 silver badges67 bronze badges
answered Sep 17, 2008 at 17:38
Cory EngebretsonCory Engebretson
7,6634 gold badges22 silver badges17 bronze badges
9
To add a Visual Studio GUI reference, you can find the DropDownStyle
options under the Properties of the selected ComboBox:
Which will automatically add the line mentioned in the first answer to the Form.Designer.cs InitializeComponent()
, like so:
this.comboBoxBatch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
answered Sep 23, 2014 at 21:44
Stay on your ComboBox and search the DropDropStyle property from the properties window and then choose DropDownList.
answered Sep 5, 2012 at 16:29
LZaraLZara
3853 silver badges5 bronze badges
Before
Method1
Method2
cmb_type.DropDownStyle=ComboBoxStyle.DropDownList
After
answered Mar 19, 2022 at 15:32
lavalava
6,1652 gold badges34 silver badges28 bronze badges
COMBOBOXID.DropDownStyle = ComboBoxStyle.DropDownList;
answered Mar 3, 2016 at 8:33
To continue displaying data in the input after selecting, do so:
VB.NET
Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
e.Handled = True
End Sub
C#
Private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
answered Jan 16, 2017 at 13:58
1
for winforms .NET change DropDownStyle to DropDownList from Combobox property
answered Jan 13, 2021 at 9:11