如何清除listBox中的所有数据



我正在寻找一个语句,该语句将清除当前listBox中的所有字符串/数据,我已经尝试过:

private void cleanlistbox(object sender, EventArgs e)
{
    listBox1.ResetText();
}

怎么样

listbox1.Items.Clear();

如果绑定到数据源,它将使用ListBox1.Items.Clear(); 引发错误

在这种情况下,您将不得不清除数据源。例如,如果它填充了Datatable:

  _dt.Clear();   //<-----Here's the Listbox emptied.
  _dt = _dbHelper.dtFillDataTable(_dt, strSQL);
  lbStyles.DataSource = _dt;
  lbStyles.DisplayMember = "YourDisplayMember";
  lbStyles.ValueMember = "YourValueMember";

试试这个:

 private void cleanlistbox(object sender, EventArgs e)
  {
     listBox1.DataSource = null;
     listBox1.Items.Clear();
  }
private void cleanlistbox(object sender, EventArgs e)
{
    listBox1.Items.Clear();
}

这应该有效:

listBox1.Items.Clear();

这应该有效:

private void cleanlistbox(object sender, EventArgs e)
{
    listBox1.Items.Clear( );
}

使用此:

listBox1.Items.Clear();

尝试

private void cleanlistbox(object sender, EventArgs e)
{
   ListBox1.Items.Clear();
}

如果使用CListBox作为指针(*),请使用此行:pList1->ResetContent();

如果您的列表框连接到作为数据源的LIST,则为listbox。Items.Clear()将不起作用。

我通常创建一个名为";DataAccess.cs";包含一个单独的类,用于使用或更改与我的表单相关的数据的代码。以下是DataAccess类的代码片段,用于清除或删除列表"中的所有项;exampleItems";

public List<ExampleItem> ClearExampleItems()
       {
           List<ExampleItem> exampleItems = new List<ExampleItem>();
           exampleItems.Clear();
           return examplelistItems;
        }

ExampleItem也在一个名为"的单独类中;ExampleItem.cs";

using System;
namespace        // The namespace is automatically added by Visual Studio
{
    public class ExampleItem
    {
        public int ItemId { get; set; }
        public string ItemType { get; set; }
        public int ItemNumber { get; set; }
        public string ItemDescription { get; set; }
        public string FullExampleItem 
        {
            get
            {
                return $"{ItemId} {ItemType} {ItemNumber} {ItemDescription}";
            }
        }
    }
}

在Window Form的代码中,以下代码片段引用了您的列表框:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Windows.Forms;
namespace        // The namespace is automatically added by Visual Studio
{
    
    public partial class YourFormName : Form
    {
        
        List<ExampleItem> exampleItems = new List<ExampleItem>();
        public YourFormName()
        {
            InitializeComponent();
            // Connect listbox to LIST
            UpdateExampleItemsBinding();
        }
        private void UpdateUpdateItemsBinding()
        {
            ExampleItemsListBox.DataSource = exampleItems;
            ExampleItemsListBox.DisplayMember = "FullExampleItem";
        }
        private void buttonClearListBox_Click(object sender, EventArgs e)
        {
            DataAccess db = new DataAccess();
            exampleItems = db.ClearExampleItems();
            
            UpdateExampleItemsBinding();
        }
    }
}

此解决方案专门针对数据源连接到列表的Windows窗体列表框。

In C#核心数据源不存在,但这很好:

listbox.ItemsSource = null;
listbox.Items.Clear();

最新更新