C#学习之ListBox,ComboBox,CheckListBox

发布时间 2023-11-06 21:38:46作者: 突破铁皮

ListBox(文本列表)

常用属性:

  • Items

    • 描述:ListBox 中的项列表。
    • 默认值:空
    • 用法:可以使用 Add(), AddRange(), Insert(), Remove(), Clear(), 等方法来对 Items 集合进行管理。
  • SelectedIndex

    • 描述:ListBox 中当前选择项的索引。
    • 默认值:-1(表示没有选中项)
    • 用法:通过设置或读取该属性来操作当前选择项的索引。
  • SelectedIndices

    • 描述:ListBox 中已选择项的集合。
    • 默认值:空
    • 用法:可以同时选择多个项。用法类似于 Items 集合。
  • SelectionMode

    • 描述:ListBox 中选择项的模式。
    • 默认值:One(表示只能选择一个项)
    • 用法:可选值包括 One、None、MultipleSimple、MultipleExtended。
  • DataSource

    • 描述:与 ListBox 关联的数据源。
    • 默认值:空
    • 用法:可将数据源设置为一个对象,这些数据将被 ListBox 显示。
  • DisplayMember

    • 描述:指定数据源中用来显示的成员。
    • 默认值:空
    • 用法:当 DataSource 属性被设置时,可指定数据源对象的哪个成员用来显示。

常用方法:

  • Add()

    • 描述:向 ListBox 中添加一个项。
    • 用法:listBox1.Items.Add("Item")
  • Remove()

    • 描述:从 ListBox 中移除一个项。
    • 用法:listBox1.Items.Remove("Item")
  • Clear()

    • 描述:清空 ListBox 中的所有项。
    • 用法:listBox1.Items.Clear()

常用事件:

  • SelectedIndexChanged

    • 描述:当选择的项发生变化时触发的事件。
  • DoubleClick

    • 描述:当用户双击 ListBox 中的项时触发的事件。

 

ComboBox(下拉菜单)

常用属性:

  • Items

    • 描述:ComboBox 中的项列表。
    • 默认值:空
    • 用法:可以使用 Add(), Remove(), Clear(), 等方法来对 Items 集合进行管理。
  • SelectedIndex

    • 描述:ComboBox 中当前选择项的索引。
    • 默认值:-1(表示没有选中项)
    • 用法:通过设置或读取该属性来操作当前选择项的索引。
  • DropDownStyle

    • 描述:ComboBox 控件的样式。
    • 默认值:DropDown(下拉列表)
    • 用法:还包括 Simple、DropDownList 等样式。
  • Text

    • 描述:ComboBox 中当前显示的文本。
    • 默认值:空
    • 用法:设置或获取当前显示的文本。
  • DataSource

    • 描述:与 ComboBox 关联的数据源。
    • 默认值:空
    • 用法:可以将 ComboBox 的数据源设置为某个对象,以便显示相关数据。

常用方法:

  • Add()

    • 描述:向 ComboBox 中添加一个项。
    • 用法:comboBox1.Items.Add("Item")
  • Remove()

    • 描述:从 ComboBox 中移除一个项。
    • 用法:comboBox1.Items.Remove("Item")
  • Clear()

    • 描述:清空 ComboBox 中的所有项。
    • 用法:comboBox1.Items.Clear()

常用事件:

  • SelectedIndexChanged

    • 描述:当选择的项发生变化时触发的事件。
  • DropDown

    • 描述:当 ComboBox 中的下拉列表展开时触发的事件。

CheckedListBox(多选列表)

常用属性:

  • CheckOnClick: 指示单击项时是否自动切换其选中状态。

    • 默认值:False
  • CheckedIndices: 返回已选定项的索引集合。

    • 默认值:Empty
  • CheckedItems: 返回已选定项的集合。

    • 默认值:Empty
  • CheckState: 获取或设置指定项的选中状态。

    • 默认值:Unchecked
  • SelectionMode: 控制选择模式,可以选择单个或多个项。

    • 默认值:One (单个选择)

常用方法:

  • GetItemCheckState(int index): 返回指定索引处项的选中状态。
  • SetItemCheckState(int index, CheckState value): 设置指定索引处项的选中状态。
  • GetItemChecked(int index): 返回指定索引处项的选中状态。

上面三个控件关键是绑定数据操作,下面是我使用上面三个控件的一个模拟图书借阅页面

启动项

using System.Data;

namespace CsharpLearn
{
    
    internal static class Program
    {
        //标明该程序为单进程
        [STAThread]
        static void Main()
        {
            ApplicationConfiguration.Initialize();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

界面绑定事件



using System.Text;
using System.Text.RegularExpressions;
using static System.Reflection.Metadata.BlobBuilder;

namespace CsharpLearn
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //初始化
            Bookshelf bookshelf = (Bookshelf)comboBox1.SelectedItem;
            checkedListBox1.Items.Clear();
            checkedListBox1.Items.AddRange(bookshelf.books.ToArray());
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //根据选中的不同类别书架更新书架上的图书
            Bookshelf bookshelf= (Bookshelf)comboBox1.SelectedItem;
            MessageBox.Show("你选择了"+bookshelf.bookshelfName);
            checkedListBox1.Items.Clear();
            checkedListBox1.Items.AddRange(bookshelf.books.ToArray());

        }
        //按钮点击事件
        private void button1_click(object sender, EventArgs e)
        {
            StringBuilder str = new StringBuilder();
            //将选中的书名添加
            foreach (int index in checkedListBox1.CheckedIndices)
            {
                str.Append(checkedListBox1.Items[index].ToString()+ Environment.NewLine);
            }
            //添加借阅时间
            str.Append("借阅时间为:"+listBox1.Items[listBox1.SelectedIndex]);
            textBox1.Text = str.ToString();

        }
    }
}

界面

namespace CsharpLearn
{
    partial class Form1
    {
        private System.ComponentModel.IContainer components = null;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            Bookshelf bookshelf1 = new Bookshelf();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            Bookshelf bookshelf2 = new Bookshelf();
            Bookshelf bookshelf3 = new Bookshelf();
            Bookshelf bookshelf4 = new Bookshelf();
            comboBox1 = new ComboBox();
            label1 = new Label();
            checkedListBox1 = new CheckedListBox();
            listBox1 = new ListBox();
            textBox1 = new TextBox();
            label2 = new Label();
            label3 = new Label();
            button1 = new Button();
            SuspendLayout();
            // 
            // comboBox1
            // 
            comboBox1.DisplayMember = "bookshelfName";
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBox1.FormattingEnabled = true;
            bookshelf1.books = new List<string>{
    "《闪灵》",
    "《德古拉》",
    "《驱魔人》",
    "《科学怪人》",
    "《小丑》",
    "《宠物坟场》",
    "《山之四十》",
    "《精神病人》",
    "《美国精神病患者》",
    "《阿米提维尔惊魂屋》"
            };
            bookshelf1.bookshelfName = "恐怖小说";
            bookshelf2.books = new List<string>{
    "《三体》",
    "《流浪地球》",
    "《黑暗森林》",
    "《时间机器》",
    "《永恒的终结》",
    "《2001太空漫游》",
    "《深渊》",
    "《银河帝国》",
    "《地球往事》",
    "《星际游民》"
            };
            bookshelf2.bookshelfName = "科幻小说";
            bookshelf3.books = new List<string>{
    "《天龙八部》",
    "《射雕英雄传》",
    "《倚天屠龙记》",
    "《神雕侠侣》",
    "《笑傲江湖》",
    "《雪山飞狐》",
    "《连城诀》",
    "《鹿鼎记》",
    "《侠客行》",
    "《侠影山城》"
        };

            bookshelf3.bookshelfName = "武侠小说";
            bookshelf4.books = new List<string>{
    "《红楼梦》",
    "《梦里花落知多少》",
    "《半生缘》",
    "《许三观卖血记》",
    "《何以笙箫默》",
    "《小时代》",
    "《我的前半生》",
    "《斗罗大陆》",
    "《天涯明月刀》",
    "《一寸相思》"
        };

            bookshelf4.bookshelfName = "爱情小说";
            //绑定数据源
            comboBox1.DataSource=new List<Bookshelf>{ bookshelf1, bookshelf2, bookshelf3, bookshelf4 };
            resources.ApplyResources(comboBox1, "comboBox1");
            comboBox1.Name = "comboBox1";
            comboBox1.ValueMember = "bookshelfName";
            comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
            // 
            // label1
            // 
            resources.ApplyResources(label1, "label1");
            label1.ForeColor = Color.DarkTurquoise;
            label1.Name = "label1";
            // 
            // checkedListBox1
            // 
            checkedListBox1.FormattingEnabled = true;
            resources.ApplyResources(checkedListBox1, "checkedListBox1");
            checkedListBox1.Name = "checkedListBox1";
            // 
            // listBox1
            // 
            listBox1.FormattingEnabled = true;
            resources.ApplyResources(listBox1, "listBox1");
            listBox1.Items.AddRange(new object[] { resources.GetString("listBox1.Items"), resources.GetString("listBox1.Items1"), resources.GetString("listBox1.Items2"), resources.GetString("listBox1.Items3"), resources.GetString("listBox1.Items4"), resources.GetString("listBox1.Items5"), resources.GetString("listBox1.Items6"), resources.GetString("listBox1.Items7"), resources.GetString("listBox1.Items8") });
            listBox1.MultiColumn = true;
            listBox1.Name = "listBox1";
            // 
            // textBox1
            // 
            resources.ApplyResources(textBox1, "textBox1");
            textBox1.Name = "textBox1";
            textBox1.ScrollBars = ScrollBars.Both;
            textBox1.Font = new Font("Arial", 10, FontStyle.Bold);
            textBox1.ReadOnly = true;
            // 
            // label2
            // 
            resources.ApplyResources(label2, "label2");
            label2.ForeColor = Color.DarkTurquoise;
            label2.Name = "label2";
            // 
            // label3
            // 
            resources.ApplyResources(label3, "label3");
            label3.ForeColor = Color.Magenta;
            label3.Name = "label3";
            // 
            // button1
            // 
            button1.BackColor = Color.Chartreuse;
            resources.ApplyResources(button1, "button1");
            button1.Name = "button1";
            button1.UseVisualStyleBackColor = false;
            button1.Click += button1_click;
            // 
            // Form1
            // 
            AutoScaleMode = AutoScaleMode.Inherit;
            resources.ApplyResources(this, "$this");
            BackColor = Color.Linen;
            Controls.Add(button1);
            Controls.Add(label3);
            Controls.Add(label2);
            Controls.Add(textBox1);
            Controls.Add(listBox1);
            Controls.Add(checkedListBox1);
            Controls.Add(label1);
            Controls.Add(comboBox1);
            ForeColor = Color.DodgerBlue;
            HelpButton = true;
            Name = "Form1";
            this.Text = "图书借阅系统";
            Load += Form1_Load;
            ResumeLayout(false);
            PerformLayout();
        }

        private ComboBox comboBox1;
        private Label label1;
        private CheckedListBox checkedListBox1;
        private ListBox listBox1;
        private TextBox textBox1;
        private Label label2;
        private Label label3;
        private Button button1;
    }
    public class Bookshelf
    {
        //这里属性必须得是公有的
        public string bookshelfName { get; set; }
        public List<string> books { get; set; }

        public Bookshelf(string bookshelfName, List<string> books)
        {
            this.bookshelfName = bookshelfName;
            this.books = books;
        }

        public Bookshelf()
        {

        }


    }
}

这里总结一下 ListBox,ComboBox,CheckListBox之间的关系,CheckListBox和ComboBox其实是ListBox的子控件,一个是CheckBox和ListBox组合,一个是TextBox与ListBox组合,这里需要注意的是采用DataSource绑定是数据源不可以再修改,即Items不能增删改,只能查看,如果想要修改需要增加一个中间控件

有关控件的详细信息可以参考官方文档

https://learn.microsoft.com/zh-cn/office/vba/api/outlook.combobox#methods