温馨提示×

c# listview怎么更新数据

小亿
160
2024-01-18 23:24:26
栏目: 编程语言

在C#中,可以通过以下步骤来更新ListView的数据:

  1. 创建一个ListView控件并设置其属性,例如列数、大小、样式等。
  2. 创建一个List对象或其他数据源,用于存储要显示在ListView中的数据。
  3. 将数据源中的数据逐个添加到ListView中的每一行中。
  4. 每当需要更新数据时,重新加载数据源,清空ListView中的数据,然后再次将新数据逐个添加到ListView中。

以下是一个简单的示例代码,演示如何更新ListView的数据:

// 创建ListView控件
ListView listView1 = new ListView();
listView1.View = View.Details;
listView1.Columns.Add("Name");
listView1.Columns.Add("Age");

// 创建数据源
List<Person> dataSource = new List<Person>();
dataSource.Add(new Person("John", 25));
dataSource.Add(new Person("Mary", 30));

// 将数据添加到ListView中
foreach(Person person in dataSource)
{
    ListViewItem item = new ListViewItem(person.Name);
    item.SubItems.Add(person.Age.ToString());
    listView1.Items.Add(item);
}

// 更新数据
dataSource.Clear();
dataSource.Add(new Person("Tom", 35));
dataSource.Add(new Person("Lisa", 28));

// 清空ListView中的数据
listView1.Items.Clear();

// 将新数据添加到ListView中
foreach(Person person in dataSource)
{
    ListViewItem item = new ListViewItem(person.Name);
    item.SubItems.Add(person.Age.ToString());
    listView1.Items.Add(item);
}

// 自定义Person类
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

上述代码首先创建了一个ListView控件,并添加了两个列(Name和Age)。然后创建了一个名为Person的简单自定义类作为数据源,用于存储要显示在ListView中的数据。在加载数据时,通过遍历数据源中的每个Person对象,依次创建ListViewItem,并将其添加到ListView中的每一行中。最后,在更新数据时,先清空ListView中的数据,然后再次将新数据逐个添加到ListView中。

请根据自己的需求修改代码,并根据实际情况进行适当的优化。

0