温馨提示×

c# listbox怎样删除选中项

c#
小樊
81
2024-10-17 00:17:28
栏目: 编程语言

在C#中,要删除ListBox中选中的项,你可以使用Items.Remove方法。以下是一个简单的示例:

using System;
using System.Windows.Forms;

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

            // 添加一些示例数据到ListBox
            listBox1.Items.Add("Item 1");
            listBox1.Items.Add("Item 2");
            listBox1.Items.Add("Item 3");
            listBox1.Items.Add("Item 4");
        }

        private void RemoveSelectedItemButton_Click(object sender, EventArgs e)
        {
            // 检查ListBox是否有选中的项
            if (listBox1.SelectedItems.Count > 0)
            {
                // 获取选中的第一个项并删除它
                listBox1.Items.Remove(listBox1.SelectedItems[0]);
            }
            else
            {
                MessageBox.Show("请选择一个项来删除。");
            }
        }
    }
}

在这个示例中,我们创建了一个包含四个项目的ListBox。当用户点击“删除选中项”按钮时,我们检查ListBox是否有选中的项。如果有,我们删除选中的第一个项。如果没有选中的项,我们会显示一个消息框提示用户选择一个项来删除。

0