Windows forms combobox запретить ввод

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's user avatar

dur

15.8k25 gold badges81 silver badges125 bronze badges

asked Mar 10, 2012 at 17:07

Iakovl's user avatar

1

Just set your combo as a DropDownList:

this.comboBoxType.DropDownStyle = ComboBoxStyle.DropDownList;

answered Mar 10, 2012 at 17:10

Reinaldo's user avatar

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

Cody Gray - on strike's user avatar

answered Mar 10, 2012 at 17:09

Justin Pihony's user avatar

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;
}

Cody Gray - on strike's user avatar

answered Nov 26, 2012 at 8:27

sherin_'s user avatar

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

Tates's user avatar

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

DevEstacion's user avatar

DevEstacionDevEstacion

1,9571 gold badge14 silver badges28 bronze badges

Morchant

1

26.09.2011, 17:46. Показов 99796. Ответов 31


Студворк — интернет-сервис помощи студентам

Как сделать, чтобы варианты можно было выбирать только из предложенных, без возможности редактирования?

kolorotur

Эксперт .NET

17366 / 12773 / 3343

Регистрация: 17.09.2011

Сообщений: 21,059

26.09.2011, 17:48

2

Лучший ответ Сообщение было отмечено как решение

Решение

C#
1
comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;



19



Morchant

26.09.2011, 18:18

3

Благодарю

15 / 15 / 7

Регистрация: 21.08.2013

Сообщений: 115

05.05.2014, 13:02

4

Однако, если это свойсво повесить в свойствай КомбоБокс-а — то вываливается ошибка.



1



Эксперт .NET

17366 / 12773 / 3343

Регистрация: 17.09.2011

Сообщений: 21,059

05.05.2014, 13:49

5

Цитата
Сообщение от mvs87
Посмотреть сообщение

вываливается ошибка.

Какая?



0



insite2012

Эксперт .NET

5495 / 4264 / 1212

Регистрация: 12.10.2013

Сообщений: 12,270

Записей в блоге: 2

05.05.2014, 20:21

6

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            comboBox1.KeyPress += (sender, e) => e.Handled = true;
        }
    }
}



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

Цитата
Сообщение от kolorotur
Посмотреть сообщение

Какая?

Во какая…
Чем побороть можно?

Миниатюры

Как запретить ввод собственного значения в ComboBox?
 



0



Эксперт .NET

17366 / 12773 / 3343

Регистрация: 17.09.2011

Сообщений: 21,059

06.05.2014, 14:13

9

Цитата
Сообщение от mvs87
Посмотреть сообщение

Во какая…

Какое отношение она имеет к запрету ввода собственного значения в выпадающий список?



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

Цитата
Сообщение от kolorotur
Посмотреть сообщение

Какое отношение она имеет к запрету ввода собственного значения в выпадающий список?

Где то натыкался что так можно. Проверил. Не вариант.

Цитата
Сообщение от Metall_Version
Посмотреть сообщение

mvs87, а что ты хочешь этим получить?

Хочу получить тоже самое, если прописать

C#
1
comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;

только в свойствах стаивть.



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

Цитата
Сообщение от Metall_Version
Посмотреть сообщение

mvs87, а в чем проблема если так и прописать?

В раздувании кода.



0



Эксперт .NET

17366 / 12773 / 3343

Регистрация: 17.09.2011

Сообщений: 21,059

07.05.2014, 11:22

14

Цитата
Сообщение от mvs87
Посмотреть сообщение

Где то натыкался что так можно. Проверил. Не вариант.
…только в свойствах стаивть.

У вас явно ошибка в коде — использование списка происходит еще до того, как свойство будет установлено.



0



Shah88

0 / 0 / 0

Регистрация: 10.11.2014

Сообщений: 1

07.02.2015, 00:32

15

C#
1
comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;

Помогло! Спасибо)



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

здравствуйте, не могли бы вы,если не сложно, поподробней объяснить, как работает эта строка?

Цитата
Сообщение от insite2012
Посмотреть сообщение

comboBox1.KeyPress += (sender, e) => e.Handled = true;

в частности, почему «+=(sender, e) =>»? что оно делает?



0



kolorotur

Эксперт .NET

17366 / 12773 / 3343

Регистрация: 17.09.2011

Сообщений: 21,059

14.04.2018, 11:04

19

Цитата
Сообщение от blackzero90
Посмотреть сообщение

что оно делает?

Подписывает на событие анонимный метод.
Эквивалентно такой записи:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            comboBox1.KeyPress += OnKeyPress;
        }
 
        void OnKeyPress(object sender, KeyPressEventArgs e)
        {
           e.Handled = true;
        }
    }

Что в свою очередь эквивалентно такой записи:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            comboBox1.KeyPress += new KeyPressEventHandler(OnKeyPress);
        }
 
        void OnKeyPress(object sender, KeyPressEventArgs e)
        {
           e.Handled = true;
        }
    }



1



387 / 265 / 117

Регистрация: 09.07.2021

Сообщений: 965

23.12.2021, 18:04

20

comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; это конечно хорошо, но оно же не даёт писать в боксе программно.
есть ли лаконичный способ запретить только ручной ввод? или всё таки придётся обрабатывать нажатия вручную?



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's user avatar

dur

15.8k25 gold badges81 silver badges125 bronze badges

asked Mar 10, 2012 at 17:07

Iakovl's user avatar

1

Just set your combo as a DropDownList:

this.comboBoxType.DropDownStyle = ComboBoxStyle.DropDownList;

answered Mar 10, 2012 at 17:10

Reinaldo's user avatar

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

Cody Gray - on strike's user avatar

answered Mar 10, 2012 at 17:09

Justin Pihony's user avatar

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;
}

Cody Gray - on strike's user avatar

answered Nov 26, 2012 at 8:27

sherin_'s user avatar

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

Tates's user avatar

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

DevEstacion's user avatar

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

  • 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;
            }
        }
    }
    

    Readonly Combobox

    Thanks,

    Sabah Shariq

    • Marked as answer by
      DotNet Wang
      Monday, May 16, 2016 12:30 PM

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.

Peter Mortensen's user avatar

asked Sep 17, 2008 at 17:37

Cory Engebretson's user avatar

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's user avatar

Omar

16.4k10 gold badges48 silver badges67 bronze badges

answered Sep 17, 2008 at 17:38

Cory Engebretson's user avatar

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:

enter image description here

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

invertigo's user avatar

Stay on your ComboBox and search the DropDropStyle property from the properties window and then choose DropDownList.

Peter Mortensen's user avatar

answered Sep 5, 2012 at 16:29

LZara's user avatar

LZaraLZara

3853 silver badges5 bronze badges

Before

enter image description here

Method1

enter image description here

Method2

cmb_type.DropDownStyle=ComboBoxStyle.DropDownList

After

enter image description here

answered Mar 19, 2022 at 15:32

lava's user avatar

lavalava

6,1652 gold badges34 silver badges28 bronze badges

COMBOBOXID.DropDownStyle = ComboBoxStyle.DropDownList;

dimitar.bogdanov's user avatar

answered Mar 3, 2016 at 8:33

Abhishek Jaiswal's user avatar

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

Diogo Rodrigues's user avatar

1

for winforms .NET change DropDownStyle to DropDownList from Combobox property

answered Jan 13, 2021 at 9:11

Rami Roosan's user avatar

  • Windows forms c текстовый редактор
  • Windows folder options windows 7
  • Windows forms c координаты мыши
  • Windows forms c примеры программ
  • Windows forms c для чайников