📌  相关文章
📜  如何在C#中设置ComboBox的大小?

📅  最后修改于: 2021-05-30 00:22:11             🧑  作者: Mango

在Windows窗体中,ComboBox在单个控件中提供了两种不同的功能,这意味着ComboBox既可以用作TextBox也可以用作ListBox。在ComboBox中,一次仅显示一个项目,其余项目显示在下拉菜单中。您可以使用Size属性为ComboBox设置大小。您可以使用两种不同的方法来设置此属性:

1.设计时:使用以下步骤设置ComboBox控件的大小是最简单的方法:

  • 第1步:创建一个Windows窗体,如下图所示:
    Visual Studio->文件->新建->项目-> WindowsFormApp
  • 步骤2:从工具箱中拖动ComboBox控件,并将其放在Windows窗体上。您可以根据需要将ComboBox控件放置在Windows窗体上的任何位置。
  • 步骤3:拖放之后,您将转到ComboBox控件的属性来设置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:最后使用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)
        {
            // Creating and setting the properties of label
            Label l = new Label();
            l.Location = new Point(222, 80);
            l.Size = new Size(99, 18);
            l.Text = "Select Your id";
      
            // Adding this label to the form
            this.Controls.Add(l);
      
            // Creating and setting the properties of comboBox
            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);
      
            // Adding this ComboBox to the form
            this.Controls.Add(mybox);
        }
    }
    }
    

    输出: