首页 > 解决方案 > 如何在按钮单击时附加文件、清除表单、加载文件和更新列表视图?

问题描述

我有一个目录表单,它在加载时在列表视图中显示 CSV 文件的内容。我正在创建一个按钮,它将三个用户输入的文本字段发送到 CSV 文件,清除表单文本框和列表视图,然后加载并在列表视图中显示更新的目录。

不幸的是,当单击按钮时,我得到一个空白列表视图,即使 clearForm 方法出现在 loadDirectory 和 displayDirectory 之前。当我注释掉 clearForm 函数时,我的列表视图包含原始列表,然后是整个新列表,正如预期的那样。

private void BtnAddNew_Click(object sender, EventArgs e)
    {
        addRecord(); // Sends text box entries to a file via. streamreader *working*
        clearForm(); // Clears the form *working on standalone clear button*
        loadDirectory(); // Loads CSV file contents to array *working*
        displayDirectory(); // Displays array to listview *working*
    }


public void loadDirectory()
    {
        StreamReader sr = new StreamReader(path);
        int lineCount = File.ReadLines(path).Count();

        string line;
        int count = -1;
        directoryTable = new record[lineCount];

        while (!sr.EndOfStream)
        {
            count++;
            line = sr.ReadLine();
            string[] fields = line.Split(',');

            record currentRecord = new record();
            currentRecord.surname = fields[0];
            currentRecord.forename = fields[1];
            currentRecord.extCode = Convert.ToInt32(fields[2]);
            directoryTable[count] = currentRecord;
        }
        sr.Close();
    }


public void displayDirectory()
    {
        for (int counter = 0; counter < directoryTable.Length; counter++)
        {
            ListViewItem lvi = new ListViewItem();
            lvi.Text = (Convert.ToString(directoryTable[counter].surname));
            lvi.SubItems.Add(Convert.ToString(directoryTable[counter].forename));
            lvi.SubItems.Add(Convert.ToString(directoryTable[counter].extCode));
            lvDirectory.Items.Add(lvi);
        }
    }


public void addRecord()
    {
        string[] newRecord = new string[3];

        newRecord[0] = txtForename.Text;
        newRecord[1] = txtSurname.Text;
        newRecord[2] = txtExtCode.Text;

        // Write newRecord array to last line of directory file
        StreamWriter sw = new StreamWriter(path, append: true);
        sw.WriteLine(newRecord[0] + ", " + newRecord[1] + ", " + newRecord[2]);
        sw.Close();
    }


public void clearForm()
    {
        foreach (Control field in Controls)
        {
            if (field is TextBox)
                ((TextBox)field).Clear();
            else if (field is ListView)
                ((ListView)field).Clear();
        }
    }

标签: c#arrayswinformslistviewtextbox

解决方案


您需要清除列表视图中的项目,而不是列表视图本身:

public void clearForm()
{
    foreach (Control field in Controls)
    {
        if (field is TextBox)
            ((TextBox)field).Clear();
        else if (field is ListView)
            ((ListView)field).Items.Clear();
    }
}

推荐阅读