【问题标题】:Reloading Listbox content重新加载列表框内容
【发布时间】:2013-03-03 18:50:10
【问题描述】:

当我看到这个帖子Here

但是在我的代码中我没有看到任何 DataBind() 方法。

lstBox.DataBind();

如何在 C#.Net 中重新加载listbox

Refresh() 方法也不行。

【问题讨论】:

  • “重新加载”是指更新列表框的数据绑定吗?
  • 是的,我从数据库中检索数据并希望在用户在 textBox 中输入文本时重新加载。

标签: c# listbox reload


【解决方案1】:

您可以尝试使用ObservableCollection 作为ItemSource,一切都会自动完成。然后您的任务是将项目填充到 ObservableCollection 中,无需手动更新。

【讨论】:

    【解决方案2】:

    DataBind() 用于 ASP.NET 控件 - 据我所知,Windows 窗体控件没有等效的方法。您的列表框的数据源是什么?我记得不久前遇到过类似的问题,我通过将控件绑定到 BindingSource 对象而不是我使用的任何对象来解决我的问题。同样,将 Listbox 绑定到 BindingSource 而不是当前数据源可能对您有利。来自MSDN

    BindingSource 组件有多种用途。首先,它通过在 Windows 窗体控件和数据源之间提供货币管理、更改通知和其他服务,简化了窗体上的控件与数据的绑定。

    换句话说,一旦您对 BindingSource 进行了更改(例如调用 BindingSource.Add,或将 BindingSource 的 DataSource 属性设置为另一个集合),您的 ListBox 将自动更新,而无需调用“DataBind()” - 类似的方法。

    如果您的列表框当前绑定到集合对象,您可以简单地将集合绑定到 BindingSource,然后将控件绑定到 BindingSource:

    BindingSource.DataSource = ListboxItems;
    ListBox.DataSource = BindingSource;
    

    您也可以手动构建 BindingSource 的内容:

    MyBindingSource.Clear();
    MyBindingSource.Add(new BusinessObject("Bill", "Clinton", 1946));
    MyBindingSource.Add(new BusinessObject("George", "Bush", 1946));
    MyBindingSource.Add(new BusinessObject("Barack", "Obama", 1961));
    
    lstBox.DataSource = MyBindingSource;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      相关资源
      最近更新 更多