简体   繁体   English

C# 从另一个 class 填充列表视图

[英]C# Populate list view from another class

I have a list view in MainForm but i want to method the code to another class named MaintenanceClass我在 MainForm 中有一个列表视图,但我想将代码传递给另一个名为 MaintenanceClass 的 class

here is the code in the MainForm to load data into the listview from a text file.这是 MainForm 中的代码,用于将数据从文本文件加载到列表视图中。

List<string> data = File.ReadAllLines(Application.StartupPath + "\\Maintenance\\" + "\\ReportFieldList\\" + "File.txt").ToList();

foreach (string d in data)
{
  string[] items = d.Split(':').Select(a => a.Trim()).ToArray();
  lvFieldList.Items.Add(new ListViewItem(items));
}

Here is the method on MaintenanceClass and its giving error that lvFieldList does not exist.这是 MaintenanceClass 上的方法及其给出的错误,即 lvFieldList 不存在。 lvFieldList is defined on the MainForm lvFieldList 在 MainForm 上定义

how can i populate the listview in the MainForm using a method in another class named MaintenanceClass?如何使用另一个名为 MaintenanceClass 的 class 中的方法填充 MainForm 中的列表视图?

在此处输入图像描述

Listview items have Text and SubItems you need to attend the first element of your array to listview item's Text value and the rest will be added as SubItems Listview 项目具有 Text 和 SubItems,您需要将数组的第一个元素加入到 listview 项目的 Text 值中,并且 rest 将作为 SubItems 添加

foreach(string d in data)
{
    string[] items = d.Split(':').Select(a => a.Trim()).ToArray();
    ListViewItem item = new ListViewItem();
    item.Text=items[0];
    for(int i=1;i<items.Count;i++)
    {
        item.SubItems.Add(items[i]);
    }
    lvFieldList.Items.Add(item);
}


You should not perform the add item to the ListView in the method reading the file.您不应在读取文件的方法中向 ListView 执行添加项目。

Below is the bare minimum for a path to take.以下是一条路径的最低要求。

Use an event as shown below.使用如下所示的事件。

public class FileOperations
{
    public delegate void ProcessLine(string[] sender);
    public event ProcessLine ProcessLineEvent;
    public void ReadFile(string fileName)
    {
        var lines = File.ReadAllLines(fileName);
        foreach (var line in lines)
        {
            ProcessLineEvent?.Invoke(line.Split(','));
        }
    }
}

Call the method in a form在表单中调用方法

var operations = new FileOperations();
operations.ProcessLineEvent += OnProcessLine;
operations.ReadFile("TODO");

Add item in this event在此事件中添加项目

private static void OnProcessLine(string[] sender)
{
    // add item
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM