【问题标题】:Data Grid won't change after deleting source file删除源文件后数据网格不会改变
【发布时间】:2017-04-16 12:35:00
【问题描述】:

我有一个 datagridview 用于显示来自文本文件的数据。然后,我有一个按钮,该按钮具有删除文本文件内容的功能(将其恢复为 0 字节)。

但是为什么事件执行(通​​过单击按钮),即使使用.refresh() 函数,数据网格也不会刷新。这是我删除文件文本内容的按钮上的代码。

private void button1_Click(object sender, EventArgs e)
{
      File.WriteAllText("Transaction.txt", String.Empty);
      dataGridView1.Refresh();
}

PS:只有在重新启动 Windows 窗体后,datagridview 才会改变(当然是空的)。

【问题讨论】:

  • 你必须重新绑定,而不是刷新。除非您使用BindingSource,否则网格不会自动与数据同步,并且使用文本文件执行此操作需要将文件访问包装在某种可枚举中。
  • 显示您如何将数据加载到DataGridView?至少您需要再次读取文件并加载数据。
  • 嗨@iMar 我只是想知道我是否解决了你的问题。

标签: c# winforms


【解决方案1】:

您需要BindingList 类将数据绑定到您的数据网格视图:

var _bindingList = new BindingList<string>();

在你的表单构造函数中:

public MyForm
{
    InitializeComponent();
    myDataGridView.BindingSource = _bindingList;
}

创建一个定时器来监控文件的变化:

DateTime lastWriteTime = DateTime.Now
private void timer_tick(object sender, EventArgs e)
{
    FileInfo f = new FileInfo("C:\\myFile.txt");
    if ( lastWriteTime == f.LastWriteTime) return;
    lastWriteTime = f.LastWriteTime;
    UpdateBindingList();
}

private void UpdateBindingList()
{
    _bindingList.Clear();
    //then read the file and add items to _bindingList.
}

【讨论】:

    猜你喜欢
    • 2012-05-21
    • 2020-11-07
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    相关资源
    最近更新 更多