我需要一条语句来清空当前在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();
}
如果您的列表框连接到数据源列表,则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}";
}
}
}
}
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表单的列表框,其数据源连接到一个列表。