c# - 如何在按钮单击时附加文件、清除表单、加载文件和更新列表视图?
问题描述
我有一个目录表单,它在加载时在列表视图中显示 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();
}
}
解决方案
您需要清除列表视图中的项目,而不是列表视图本身:
public void clearForm()
{
foreach (Control field in Controls)
{
if (field is TextBox)
((TextBox)field).Clear();
else if (field is ListView)
((ListView)field).Items.Clear();
}
}
推荐阅读
- c# - ObservableCollection.Clear() 抛出异常“索引超出范围”
- sphinx - 为什么 Sphinx 没有带字段权重的 BM25?
- single-sign-on - ASWebAuthenticationSession 只显示取消按钮
- facebook - FB.login 如果用户之前连接过应用程序,则区分成功登录和取消
- json - 期望包含的属性名称... || 无法打开json文件
- html - 移动(变换:翻译(x,y))文本(
) 在一个 div 中,使它看起来像是隐藏在同一个 div 中
- visual-studio - MSI 进度条前关于程序和功能的 Wix 卸载确认对话框(是/否)
- angular - 如何在页面显示之前将数据从我的组件获取到 Angular 中的 html 中?
- python - 使用另一个 dict 列表中的键对 dict 列表进行排序
- java - 转换 JavaPairDStream
到 JavaPairDStream ,在元组中切换值(Java Spark)