2023/11/17——C#——ListBox、comboBox、PictureBox、Timer

本文详细介绍了WinForms中常见的控件:ListBox、ComboBox和PictureBox的创建、属性和使用示例。同时,讨论了这两者之间的区别,以及Timer控件的使用,用于定时触发事件。
摘要由CSDN通过智能技术生成

1.ListBox

在WinForms中,ListBox是一种常用的控件,用于显示项目列表。你可以通过Visual Studio或者手动创建一个ListBox,并对其进行操作。

Visual Studio中创建ListBox:

  1. 使用Visual Studio创建ListBox

    • 打开Visual Studio并创建一个新的WinForms应用程序项目。
    • 打开窗体设计器,从工具箱中拖拽ListBox控件到窗体上。
  2. 常用属性和方法

    • Items:这个属性代表了ListBox中的项目集合。
    • SelectionMode:可以设置选择模式,如单选或多选。
    • SelectedIndex:用于获取或设置当前选择项目的索引。
    • SelectedItems:表示被选中的项目的集合。
    • 添加项目:通过Items.Add()方法向ListBox中添加项目。
    • 移除项目:通过Items.Remove()方法或Items.RemoveAt()方法移除项目。

下面是一个简单的示例代码,演示了如何使用ListBox控件:

using System;
using System.Windows.Forms;

namespace ListBoxExample
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            // 向ListBox中添加项目
            listBoxItems.Items.Add(txtNewItem.Text);
            txtNewItem.Clear();
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            // 移除选中的项目
            if (listBoxItems.SelectedIndex != -1)
            {
                listBoxItems.Items.RemoveAt(listBoxItems.SelectedIndex);
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            // 清空ListBox中的所有项目
            listBoxItems.Items.Clear();
        }

        private void btnSelectedItems_Click(object sender, EventArgs e)
        {
            // 获取选中的项目
            string selectedItems = "";
            foreach (var item in listBoxItems.SelectedItems)
            { <

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值