【问题标题】:Can't refresh datagridview with bindingsource无法使用 bindingsource 刷新 datagridview
【发布时间】:2011-03-14 20:18:53
【问题描述】:

目标:
单击添加或删除按钮后,应使用文档中的最新数据刷新 datagridview。

问题:

datagridview 无法刷新 通过删除或进行更改后 添加新数据。

我正在使用与 datagridview 的数据源链接的绑定源。

我用不同的解决方案尝试了一切,并阅读了不同论坛的建议,但我仍然无法解决这个问题。

我也尝试使用这些语法“BindingSource.ResetBindings(false)”、“BindingSource.Refresh()”等,但没有结果。

以下链接:

How to refresh a bindingsource

http://www.eggheadcafe.com/community/aspnet/2/10114324/datagridview-refresh-from-another-form.aspx

http://blogs.msdn.com/b/dchandnani/archive/2005/03/15/396387.aspx

http://bytes.com/topic/c-sharp/answers/812061-problem-refresh-datagridview

    bSrcStock.DataSource = myProductrepository.GetAllProductList();


    dgridStock.DataSource = null;
    dgridStock.DataSource = bSrcStock;
    bSrcStock.ResetBindings(true);


    dgridStock.Columns[0].Width = 101;
    dgridStock.Columns[1].Width = 65;
    dgridStock.Columns[2].Width = 80;
    dgridStock.Columns[3].Width = 120;
    dgridStock.Columns[4].Width = 90;

【问题讨论】:

  • 你的数据网格绑定到什么?
  • 仅供参考;您不需要设置 dgridStock.DataSource = null;如果您还没有实现 BindingSource,这只是一种方法!
  • 你的列表项类型是否实现了 INotifyPropetyChanged 接口?

标签: c# datagridview bindingsource


【解决方案1】:

我遇到了同样的问题,发现问题出在静态构造函数中的 BindingSource 初始化(该类是单例)。意识到这一点后,我将代码移到了调用事件中,它终于可以正常工作,而无需分配 null 或调用 clear 方法。希望这会有所帮助。

【讨论】:

    【解决方案2】:

    无需定义列(除非您真的想...)

    然后,每次在列表中添加或删除某些内容时,只需调用 refreshDataGridView 方法...

        public List<CustomItem> ciList = new List<CustomItem>();
    
        CustomItem tempItem = new CustomItem();
        tempItem.Name = "Test Name";
    
        ciList.add(tempItem);
        refreshDataGridView();
    
        private void refreshDataGridView()
        {
            dataGridView1.DataSource = typeof(List<>);
            dataGridView1.DataSource = ciList;
            dataGridView1.AutoResizeColumns();
            dataGridView1.Refresh();
        }
    

    【讨论】:

      【解决方案3】:

      您需要一个列表,以便在添加项目等时通知 BindingSource。为此使用 System.ComponentModel.BindingList。

      Dim lisItems As New System.ComponentModel.BindingList(Of myObject)
      

      效果很好!仅缺少 AddRange,因此可以解决此问题:

      Private Sub AddRange(ByVal lis As List(Of myObject))
          For Each itm In lis
              lisItems.Add(itm)
          Next
      End Sub
      

      https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.bindinglist-1?view=netframework-4.7.2

      【讨论】:

        猜你喜欢
        • 2015-11-04
        • 1970-01-01
        • 2016-07-24
        • 2013-12-21
        • 1970-01-01
        • 2016-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多