C#对ListBox控件中的数据进行的操作

目录

1.添加数据:

2.删除数据:

3.清空数据:

4.选择项:

5.排序:

6.获取选中的项:

7.获取ListBox中的所有项:

8.综合示例


C#中对ListBox控件中的数据进行的操作主要包括添加、删除、清空、选择、排序等。

1.添加数据:

cs 复制代码
// 添加一个字符串数组
listBox1.Items.AddRange(new string[] { "item1", "item2", "item3" });

// 或者添加单个字符串
listBox1.Items.Add("item4");

2.删除数据:

cs 复制代码
// 删除选定的项
listBox1.Items.Remove(listBox1.SelectedItem);

// 或者删除第n项
listBox1.Items.RemoveAt(n);

3.清空数据:

cs 复制代码
listBox1.Items.Clear();

4.选择项:

cs 复制代码
// 选择第n项
listBox1.SelectedIndex = n;

// 或者选择包含特定文本的项
for (int i = 0; i < listBox1.Items.Count; i++)
{
    if (listBox1.Items[i].ToString() == "item4")
    {
        listBox1.SelectedIndex = i;
        break;
    }
}

5.排序:

cs 复制代码
//listBox1排序);
listBox1.Sorted = true;

6.获取选中的项:

cs 复制代码
int selectedIndex = listBox1.SelectedIndex;

7.获取ListBox中的所有项:

cs 复制代码
List<string> allItems = new List<string>();
foreach (string item in listBox1.Items)
{
    allItems.Add(item.ToString());
}

8.综合示例

cs 复制代码
// ListBox控件操作
using System.Diagnostics;
using System.Linq;
namespace _148_2
{
    public partial class Form1 : Form
    {
        private static ListBox? listBox1;
        private Button? button1;
        private static TextBox? textBox1;
        private Button? button2;
        private Button? button3;
        private Button? button4;

        public Form1()
        {
            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;
            Load += Form1_Load;
        }

        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // listBox1
            // 
            listBox1 = new ListBox
            {
                FormattingEnabled = true,
                ItemHeight = 17,
                Location = new Point(12, 12),
                Name = "listBox1",
                Size = new Size(270, 174),
                TabIndex = 1
            };
            // 
            // button1
            // 
            button1 = new Button
            {
                ForeColor = SystemColors.ActiveCaptionText,
                TabIndex = 2,
                Text = "操作",
                UseVisualStyleBackColor = true,
                Location = new Point(231, 221),
                Name = "button1",
                Size = new Size(50, 23)
            };
            button1.Click += Button1_Click;
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(12, 192),
                Name = "textBox1",
                Size = new Size(270, 23),
                TabIndex = 3
            };
            // 
            // button2
            // 
            button2 = new Button
            {
                ForeColor = SystemColors.ActiveCaptionText,
                TabIndex = 4,
                Text = "清空",
                UseVisualStyleBackColor = true,
                Location = new Point(166, 221),
                Name = "button2",
                Size = new Size(49, 23)
            };
            button2.Click += Button2_Click;
            // 
            // button3
            // 
            button3 = new Button
            {
                ForeColor = SystemColors.ActiveCaptionText,
                Location = new Point(12, 221),
                Name = "button3",
                Size = new Size(75, 23),
                TabIndex = 5,
                Text = "复制全部",
                UseVisualStyleBackColor = true
            };
            button3.Click += Button3_Click;
            // 
            // button4
            // 
            button4 = new Button
            {
                ForeColor = SystemColors.ActiveCaptionText,
                Location = new Point(103, 221),
                Name = "button4",
                Size = new Size(47, 23),
                TabIndex = 6,
                Text = "删除",
                UseVisualStyleBackColor = true
            };
            button4.Click += Button4_Click;
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(294, 255);
            Controls.Add(button4);
            Controls.Add(button3);
            Controls.Add(button2);
            Controls.Add(textBox1);
            Controls.Add(button1);
            Controls.Add(listBox1);
            ForeColor = SystemColors.ControlLightLight;
            Name = "Form1";
            Text = "ListBox操作";
        }

        private void Button1_Click(object? sender, EventArgs e)
        {
            ListBoxOperations();
        }

        private static void ListBoxOperations()
        {
            // 创建一个字符串数组
            string[] items = ["item3", "item2", "item1"];

            // 添加字符串数组到ListBox
            listBox1!.Items.AddRange(items);

            // 添加单个字符串到ListBox
            listBox1.Items.Add("item4");

            //listBox1排序
            listBox1.Sorted = true;

            // 选择第2个项(索引从0开始)
            listBox1.SelectedIndex = 1;

            // 获取选中的项
            string selectedValue = listBox1.SelectedItem!.ToString()!;
            textBox1!.Text = "Selected Value: " + selectedValue;

            // 获取选中的项的索引
            int selectedIndex = listBox1.SelectedIndex;
            textBox1!.Text += "  Selected Index: " + selectedIndex;
        }
        // 清空所有
        private void Button2_Click(object? sender, EventArgs e)
        {
            listBox1!.Items.Clear();
        }
        // 复制并添加全部
        private void Button3_Click(object? sender, EventArgs e)
        {
            List<string> allItems = [];
            foreach (string item in listBox1!.Items)
            {
                allItems.Add(item.ToString());
            }
            foreach (string item in allItems)
            {
                listBox1.Items.Add(item);
            }
        }
        // 删除选中
        private void Button4_Click(object? sender, EventArgs e)
        {
            listBox1!.Items.Remove(listBox1.SelectedItem!);
        }
    }
}
相关推荐
Ronin30519 分钟前
【C++】类型转换
开发语言·c++
mrbone1135 分钟前
Git-git worktree的使用
开发语言·c++·git·cmake·worktree·gitab
浪裡遊1 小时前
Sass详解:功能特性、常用方法与最佳实践
开发语言·前端·javascript·css·vue.js·rust·sass
真实的菜1 小时前
JVM类加载系统详解:深入理解Java类的生命周期
java·开发语言·jvm
代码讲故事1 小时前
多种方法实现golang中实现对http的响应内容生成图片
开发语言·chrome·http·golang·图片·快照·截图
虾球xz2 小时前
CppCon 2018 学习:EFFECTIVE REPLACEMENT OF DYNAMIC POLYMORPHISM WITH std::variant
开发语言·c++·学习
Allen_LVyingbo2 小时前
Python常用医疗AI库以及案例解析(2025年版、上)
开发语言·人工智能·python·学习·健康医疗
小哈龙2 小时前
裸仓库 + Git Bash 搭建 本地 Git 服务端与客户端
开发语言·git·bash
唐青枫2 小时前
C#.NET log4net 详解
c#·.net
G探险者2 小时前
《如何在 Spring 中实现 MQ 消息的自动重连:监听与发送双通道策略》
java·开发语言·rpc