C# ComboBox:组合框控件

       在 C# WinForm开发中组合框(ComboBox)控件也称下拉列表框,网络

 用于选择所需的选项,例如在注册学生信息时选择学历、专业等。
 
        使用组合框能够有效地避免非法值的输入。

在组合框中也有一些常用的属性,以下表所示。spa

       在组合框中经常使用的事件是改变组合框中的值时发生的,即组合框中的选项改变事件 SelectedlndexChanged。.net

【实例】code

            实现一个选择专业的实例。orm

Form1.csblog

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 ComboBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //窗体加载事件,为组合框添加值
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("计算机应用");
            comboBox1.Items.Add("英语");
            comboBox1.Items.Add("会计");
            comboBox1.Items.Add("软件工程");
            comboBox1.Items.Add("网络工程");
        }

        //组合框中选项改变的事件
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //当组合框中选择的值发生变化时弹出消息框显示当前组合框中选择的值
            MessageBox.Show("您选择的专业是:" + comboBox1.Text, "提示");
        }

        //“添加”按钮的单击事件,用于向组合框中添加文本框中的值
        private void button1_Click(object sender, EventArgs e)
        {
            //判断文本框中是否为空,不为空则将其添加到组合框中
            if (textBox2.Text != "")
            {
                //判断文本框中的值是否与组合框中的的值重复
                if (comboBox1.Items.Contains(textBox2.Text))
                {
                    MessageBox.Show("该专业已存在!");
                }
                else
                {
                    comboBox1.Items.Add(textBox2.Text);
                    MessageBox.Show("添加成功!");
                }
            }
            else
            {
                MessageBox.Show("请输入专业!", "提示");
            }
        }

        //“删除按钮的单击事件,用于删除文本框中输入的值”
        private void button2_Click(object sender, EventArgs e)
        {
            //判断文本框是否为空
            if (textBox2.Text != "")
            {
                //判断组合框中是否存在文本框中输入的值
                if (comboBox1.Items.Contains(textBox2.Text))
                {
                    comboBox1.Items.Remove(textBox2.Text);
                    MessageBox.Show("删除成功!");
                }
                else
                {
                    MessageBox.Show("您输入的专业不存在", "提示");
                }
            }
            else 
            {
                MessageBox.Show("请输入要删除的专业", "提示");
            }
        }
 
    }
}

Program.cs事件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace ComboBox
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}