Как изменить размер combobox

I have a ComboBox on a form, and its default height is 21. How do I change it?

To do this, you need to set the DrawMode to OwnerDrawVariable or OwnerDrawFixed and manually draw your items. This can be done with a pretty simple class.

This example will allow you to use the ItemHeight property of the ComboBox regardless of font size. I threw in an bonus property TextAlign which will also allow you to center the items.

One thing worth mentioning is, you must set DropDownStyle to DropDownList for the selected item to respect our customizations.

// The standard combo box height is determined by the font. This means, if you want a large text box, you must use a large font.
// In our class, ItemHeight will now determine the height of the combobox with no respect to the combobox font.
// TextAlign can be used to align the text in the ComboBox
class UKComboBox : ComboBox
{

    private StringAlignment _textAlign = StringAlignment.Center;
    [Description("String Alignment")]
    [Category("CustomFonts")]
    [DefaultValue(typeof(StringAlignment))]
    public StringAlignment TextAlign
    {
        get { return _textAlign; }
        set
        {
            _textAlign = value;
        }
    }

    private int _textYOffset = 0;
    [Description("When using a non-centered TextAlign, you may want to use TextYOffset to manually center the Item text.")]
    [Category("CustomFonts")]
    [DefaultValue(typeof(int))]
    public int TextYOffset
    {
        get { return _textYOffset; }
        set
        {
            _textYOffset = value;
        }
    }


    public UKComboBox()
    {
            // Set OwnerDrawVariable to indicate we will manually draw all elements.
            this.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
            // DropDownList style required for selected item to respect our DrawItem customizations.
            this.DropDownStyle = ComboBoxStyle.DropDownList;
            // Hook into our DrawItem & MeasureItem events
            this.DrawItem +=
                new DrawItemEventHandler(ComboBox_DrawItem);
            this.MeasureItem +=
                new MeasureItemEventHandler(ComboBox_MeasureItem);

    }

    // Allow Combo Box to center aligned and manually draw our items
    private void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
    {


        // Draw the background
        e.DrawBackground();

        // Draw the items
        if (e.Index >= 0)
        {
            // Set the string format to our desired format (Center, Near, Far)
            StringFormat sf = new StringFormat();
            sf.LineAlignment = _textAlign;
            sf.Alignment = _textAlign;

            // Set the brush the same as our ForeColour
            Brush brush = new SolidBrush(this.ForeColor);

            // If this item is selected, draw the highlight
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                brush = SystemBrushes.HighlightText;

            // Draw our string including our offset.
            e.Graphics.DrawString(this.Items[e.Index].ToString(), this.Font, brush, 
                new RectangleF(e.Bounds.X, e.Bounds.Y + _textYOffset, e.Bounds.Width, e.Bounds.Height), sf);
        }

    }


    // If you set the Draw property to DrawMode.OwnerDrawVariable, 
    // you must handle the MeasureItem event. This event handler 
    // will set the height and width of each item before it is drawn. 
    private void ComboBox_MeasureItem(object sender,System.Windows.Forms.MeasureItemEventArgs e)
    {
        // Custom heights per item index can be done here.
    }

}

Now we have full control over our font and height of the ComboBox separately. We no longer need to make a large font to size our ComboBox.

enter image description here

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    In Windows forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to set the size to your ComboBox by using Size Property. You can set this property using two different methods:

    1. Design-Time: It is the easiest method to set the size of the ComboBox control as using the following steps:

    • Step 1: Create a windows form as shown in the below image:
      Visual Studio -> File -> New -> Project -> WindowsFormApp
    • Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need.
    • Step 3: After drag and drop you will go to the properties of the ComboBox control to set the size of the ComboBox.

      Output:

    2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the size of the ComboBox programmatically with the help of given syntax:

    public System.Drawing.Size Size { get; set; }

    Here, the Size indicates the height and width of the ComboBox in pixels. Following steps are used to set the size of the ComboBox:

    • Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.
      // Creating ComboBox using ComboBox class
      ComboBox mybox = new ComboBox();
      
    • Step 2: After creating ComboBox, set the size of the ComboBox.
      // Set the size of the combobox
      mybox.Size = new Size(216, 26);
      
    • Step 3: And last add this combobox control to form using Add() method.
      // Add this ComboBox to form
      this.Controls.Add(mybox);
      

      Example:

      using System;

      using System.Collections.Generic;

      using System.ComponentModel;

      using System.Data;

      using System.Drawing;

      using System.Linq;

      using System.Text;

      using System.Threading.Tasks;

      using System.Windows.Forms;

      namespace WindowsFormsApp11 {

      public partial class Form1 : Form {

          public Form1()

          {

              InitializeComponent();

          }

          private void Form1_Load(object sender, EventArgs e)

          {

              Label l = new Label();

              l.Location = new Point(222, 80);

              l.Size = new Size(99, 18);

              l.Text = "Select Your id";

              this.Controls.Add(l);

              ComboBox mybox = new ComboBox();

              mybox.Location = new Point(327, 77);

              mybox.Size = new Size(216, 26);

              mybox.Name = "My_Cobo_Box";

              mybox.Items.Add(230);

              mybox.Items.Add(231);

              mybox.Items.Add(232);

              mybox.Items.Add(233);

              mybox.Items.Add(234);

              this.Controls.Add(mybox);

          }

      }

      }

      Output:

    • Remove From My Forums
    • Question

    • I need to know, how to change ComboBox height without changing its font size.

      Can any body help me?

      • Edited by

        Wednesday, August 6, 2014 6:56 AM

    Answers

    • Hi Carl,

      Thank you for your suggestion.

      I have tried the suggestion provided in your reply and i could find only drop down item item size gets increased. 

      Can you please share me the code snippet to achieve this?

      Thanks,

      Kannan.R

      Hi,

      I recreated a simple sample which you could download it from
      http://1drv.ms/1pfXrHB.

      And we could need the following step.

      1. set its DrawMode to OwnerDrawVariable, then draw that text for these items within DrawItem event.

      2. set its ItemHeight to the size you wanted with its properties viewer.

      Regards.


      We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.

      Click
      HERE to participate the survey.

      • Marked as answer by
        Carl Cai
        Friday, August 15, 2014 8:53 AM

    • Hi Carl,

      Thank you so much.

      This solution works for standard combobox. In my custom combobox all the api and functions are modified from scratch. Hence this solution does not works in that.   And i cannot share any of its code snippet. 

      Is there any way to force control remeasure combobox itemheight when ever user likes?

      I have tried

      invalidate()

      RefreshItems()

      SendMessage(combobox.handle,setcmitemheight,-1,itemheight)

      nothing works.

      Thanks,

      Kannan.R

      Hi,

      If that is not a standed combobox, and if you tested with both MeasureItem event and the Designer view to change its itemHeight, I am afraid that I will agree with Magnus that there is no such way to get that done, since

      size to fit the size of its font, and the way for standed combobox is just to draw the items by ourselves.

      Regards.


      We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.

      Click
      HERE to participate the survey.

      • Marked as answer by
        Carl Cai
        Friday, August 15, 2014 8:53 AM

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    In Windows Forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to set the height in pixels of the drop-down list in your ComboBox by using the DropDownHeight Property. You can set this property using two different methods:

    1. Design-Time: It is the easiest method to set the DropDownHeight property of the ComboBox control using the following steps:

    • Step 1: Create a windows form as shown in the below image:
      Visual Studio -> File -> New -> Project -> WindowsFormApp
    • Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need.
    • Step 3: After drag and drop you will go to the properties of the ComboBox control to set the DropDownHeight property of the ComboBox.

      Output:

    2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the height of the drop-down list in the ComboBox programmatically with the help of given syntax:

    public int DropDownHeight { get; set; }

    Here, the value of this property is of System.Int32 type. It will throw an ArgumentException if the value of this property is less than one. Following steps are used to set the DropDownHeight Property of the ComboBox elements:

    • Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.
      // Creating ComboBox using ComboBox class
      ComboBox mybox = new ComboBox();
      
    • Step 2: After creating ComboBox, set the DropDownHeight property of the ComboBox provided by the ComboBox class.
      // Set DropDownHeight property of the combobox
      mybox.DropDownHeight = 26;
      
    • Step 3: And last add this combobox control to form using Add() method.
      // Add this ComboBox to form
      this.Controls.Add(mybox);
      

      Example:

      using System;

      using System.Collections.Generic;

      using System.ComponentModel;

      using System.Data;

      using System.Drawing;

      using System.Linq;

      using System.Text;

      using System.Threading.Tasks;

      using System.Windows.Forms;

      namespace WindowsFormsApp14 {

      public partial class Form1 : Form {

          public Form1()

          {

              InitializeComponent();

          }

          private void Form1_Load(object sender, EventArgs e)

          {

              Label l = new Label();

              l.Location = new Point(222, 80);

              l.Size = new Size(99, 18);

              l.Text = "Select Id";

              this.Controls.Add(l);

              ComboBox mybox = new ComboBox();

              mybox.Location = new Point(327, 77);

              mybox.Size = new Size(216, 26);

              mybox.MaxLength = 3;

              mybox.DropDownStyle = ComboBoxStyle.DropDown;

              mybox.DropDownHeight = 26;

              mybox.Items.Add(240);

              mybox.Items.Add(241);

              mybox.Items.Add(242);

              mybox.Items.Add(243);

              mybox.Items.Add(244);

              this.Controls.Add(mybox);

          }

      }

      }

      Output:

      Before setting drop-down height:

      After setting drop-down height:

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    In Windows Forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to set the height in pixels of the drop-down list in your ComboBox by using the DropDownHeight Property. You can set this property using two different methods:

    1. Design-Time: It is the easiest method to set the DropDownHeight property of the ComboBox control using the following steps:

    • Step 1: Create a windows form as shown in the below image:
      Visual Studio -> File -> New -> Project -> WindowsFormApp
    • Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need.
    • Step 3: After drag and drop you will go to the properties of the ComboBox control to set the DropDownHeight property of the ComboBox.

      Output:

    2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the height of the drop-down list in the ComboBox programmatically with the help of given syntax:

    public int DropDownHeight { get; set; }

    Here, the value of this property is of System.Int32 type. It will throw an ArgumentException if the value of this property is less than one. Following steps are used to set the DropDownHeight Property of the ComboBox elements:

    • Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.
      // Creating ComboBox using ComboBox class
      ComboBox mybox = new ComboBox();
      
    • Step 2: After creating ComboBox, set the DropDownHeight property of the ComboBox provided by the ComboBox class.
      // Set DropDownHeight property of the combobox
      mybox.DropDownHeight = 26;
      
    • Step 3: And last add this combobox control to form using Add() method.
      // Add this ComboBox to form
      this.Controls.Add(mybox);
      

      Example:

      using System;

      using System.Collections.Generic;

      using System.ComponentModel;

      using System.Data;

      using System.Drawing;

      using System.Linq;

      using System.Text;

      using System.Threading.Tasks;

      using System.Windows.Forms;

      namespace WindowsFormsApp14 {

      public partial class Form1 : Form {

          public Form1()

          {

              InitializeComponent();

          }

          private void Form1_Load(object sender, EventArgs e)

          {

              Label l = new Label();

              l.Location = new Point(222, 80);

              l.Size = new Size(99, 18);

              l.Text = "Select Id";

              this.Controls.Add(l);

              ComboBox mybox = new ComboBox();

              mybox.Location = new Point(327, 77);

              mybox.Size = new Size(216, 26);

              mybox.MaxLength = 3;

              mybox.DropDownStyle = ComboBoxStyle.DropDown;

              mybox.DropDownHeight = 26;

              mybox.Items.Add(240);

              mybox.Items.Add(241);

              mybox.Items.Add(242);

              mybox.Items.Add(243);

              mybox.Items.Add(244);

              this.Controls.Add(mybox);

          }

      }

      }

      Output:

      Before setting drop-down height:

      After setting drop-down height:

    Для этого нужно установить DrawMode в OwnerDrawVariable or OwnerDrawFixed и вручную нарисуйте свои предметы. Это можно сделать с помощью довольно простого класса.

    Этот пример позволит вам использовать ItemHeight свойство ComboBox независимо от размера шрифта. Я добавил бонусную недвижимость TextAlign что также позволит вам центрировать предметы.

    Стоит упомянуть одну вещь: вы должны установить DropDownStyle в DropDownList для выбранного элемента с учетом наших настроек.

    // The standard combo box height is determined by the font. This means, if you want a large text box, you must use a large font.
    // In our class, ItemHeight will now determine the height of the combobox with no respect to the combobox font.
    // TextAlign can be used to align the text in the ComboBox
    class UKComboBox : ComboBox
    {
    
        private StringAlignment _textAlign = StringAlignment.Center;
        [Description("String Alignment")]
        [Category("CustomFonts")]
        [DefaultValue(typeof(StringAlignment))]
        public StringAlignment TextAlign
        {
            get { return _textAlign; }
            set
            {
                _textAlign = value;
            }
        }
    
        private int _textYOffset = 0;
        [Description("When using a non-centered TextAlign, you may want to use TextYOffset to manually center the Item text.")]
        [Category("CustomFonts")]
        [DefaultValue(typeof(int))]
        public int TextYOffset
        {
            get { return _textYOffset; }
            set
            {
                _textYOffset = value;
            }
        }
    
    
        public UKComboBox()
        {
                // Set OwnerDrawVariable to indicate we will manually draw all elements.
                this.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
                // DropDownList style required for selected item to respect our DrawItem customizations.
                this.DropDownStyle = ComboBoxStyle.DropDownList;
                // Hook into our DrawItem & MeasureItem events
                this.DrawItem +=
                    new DrawItemEventHandler(ComboBox_DrawItem);
                this.MeasureItem +=
                    new MeasureItemEventHandler(ComboBox_MeasureItem);
    
        }
    
        // Allow Combo Box to center aligned and manually draw our items
        private void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
        {
    
    
            // Draw the background
            e.DrawBackground();
    
            // Draw the items
            if (e.Index >= 0)
            {
                // Set the string format to our desired format (Center, Near, Far)
                StringFormat sf = new StringFormat();
                sf.LineAlignment = _textAlign;
                sf.Alignment = _textAlign;
    
                // Set the brush the same as our ForeColour
                Brush brush = new SolidBrush(this.ForeColor);
    
                // If this item is selected, draw the highlight
                if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                    brush = SystemBrushes.HighlightText;
    
                // Draw our string including our offset.
                e.Graphics.DrawString(this.Items[e.Index].ToString(), this.Font, brush, 
                    new RectangleF(e.Bounds.X, e.Bounds.Y + _textYOffset, e.Bounds.Width, e.Bounds.Height), sf);
            }
    
        }
    
    
        // If you set the Draw property to DrawMode.OwnerDrawVariable, 
        // you must handle the MeasureItem event. This event handler 
        // will set the height and width of each item before it is drawn. 
        private void ComboBox_MeasureItem(object sender,System.Windows.Forms.MeasureItemEventArgs e)
        {
            // Custom heights per item index can be done here.
        }
    
    }
    

    Теперь у нас есть полный контроль над шрифтом и высотой ComboBox по отдельности. Нам больше не нужно делать большой шрифт для размера нашего ComboBox.

    Введите описание изображения здесь

    29.12.2019C#

    В формах Windows ComboBox предоставляет две разные функции в одном элементе управления, это означает, что ComboBox работает как TextBox и ListBox. В ComboBox одновременно отображается только один элемент, а остальные элементы отображаются в раскрывающемся меню. Вы можете установить размер для вашего ComboBox с помощью свойства размера . Вы можете установить это свойство двумя разными способами:

    1. Время разработки: это самый простой способ установить размер элемента управления ComboBox, используя следующие шаги:

    2. Время выполнения: это немного сложнее, чем описанный выше метод. В этом методе вы можете установить размер ComboBox программно с помощью данного синтаксиса:

    public System.Drawing.Size Size { get; set; }

    Здесь Размер указывает высоту и ширину ComboBox в пикселях. Следующие шаги используются для установки размера ComboBox:

    • Шаг 1. Создайте комбинированный список с помощью конструктора ComboBox (), предоставляемого классом ComboBox.
      // Creating ComboBox using ComboBox class
      ComboBox mybox = new ComboBox();
      
    • Шаг 2: После создания ComboBox установите размер ComboBox.
      // Set the size of the combobox
      mybox.Size = new Size(216, 26);
      
    • Шаг 3: И наконец добавьте этот элемент управления combobox в форму, используя метод Add ().
      // Add this ComboBox to form
      this.Controls.Add(mybox);
      

      Пример:

      using System;

      using System.Collections.Generic;

      using System.ComponentModel;

      using System.Data;

      using System.Drawing;

      using System.Linq;

      using System.Text;

      using System.Threading.Tasks;

      using System.Windows.Forms;

      namespace WindowsFormsApp11 {

      public partial class Form1 : Form {

          public Form1()

          {

              InitializeComponent();

          }

          private void Form1_Load(object sender, EventArgs e)

          {

              Label l = new Label();

              l.Location = new Point(222, 80);

              l.Size = new Size(99, 18);

              l.Text = "Select Your id";

              this.Controls.Add(l);

              ComboBox mybox = new ComboBox();

              mybox.Location = new Point(327, 77);

              mybox.Size = new Size(216, 26);

              mybox.Name = "My_Cobo_Box";

              mybox.Items.Add(230);

              mybox.Items.Add(231);

              mybox.Items.Add(232);

              mybox.Items.Add(233);

              mybox.Items.Add(234);

              this.Controls.Add(mybox);

          }

      }
      }

      Выход:

    Рекомендуемые посты:

    • C # | Проверьте, имеет ли Hashtable фиксированный размер
    • Как установить размер RadioButton в C #?
    • C # | Создание HybridDictionary с указанным начальным размером и чувствительностью к регистру
    • C # | Проверьте, имеет ли ArrayList фиксированный размер
    • C # | Проверьте, имеет ли объект SortedList фиксированный размер
    • C # | Проверьте, имеет ли ListDictionary фиксированный размер
    • C # | Проверьте, имеет ли HybridDictionary фиксированный размер
    • C # | Создание чувствительного к регистру HybridDictionary с указанным начальным размером
    • C # | Как изменить размер одномерного массива
    • C # | Проверьте, имеет ли массив фиксированный размер или нет
    • Как установить размер кнопки в C #?
    • Как установить расположение ComboBox в C #?
    • Как установить имя ComboBox в C #?
    • Как добавить элементы в ComboBox в C #?
    • Как отсортировать элементы ComboBox в C #?

    Как установить размер ComboBox в C #?

    0.00 (0%) 0 votes

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Как изменить размер checkbox html
  • Как изменить размер checkbox css
  • Как изменить размер button html
  • Как изменить размер bootcamp на mac
  • Как изменить размер bitmap c

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии