如何在单击按钮时附加文件,清除表单,加载文件并更新listview?

问题描述 投票:0回答:1

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

[不幸的是,当单击按钮时,即使clearForm方法位于loadDirectory和displayDirectory之前,但我最终得到的都是空白列表视图。当我注释掉clearForm函数时,我的listview包含原始列表,然后按预期包含整个新列表。

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# arrays winforms listview textbox
1个回答
0
投票
public void clearForm() { foreach (Control field in Controls) { if (field is TextBox) ((TextBox)field).Clear(); else if (field is ListView) ((ListView)field).Items.Clear(); } }
© www.soinside.com 2019 - 2024. All rights reserved.