ListBox has set datasource but Refresh does nothing

妖精的绣舞 提交于 2019-12-04 22:51:16

问题


I seem to be misunderstanding the ListBox.Refresh() method and I was hoping someone could help me out.

What I am trying to do:
I want to load a listbox's data (source = table of a sql database) upon initialization of a windows form. Also when the user adds data to the database I would like the listbox to update.

Logic:
I have a sql database as my source, it is set as:

listBoxDays.DataSource = DBQuery.informationRetreval().DefaultView;

DBquery.informationRetreval() is a static method within the my DBQuery static class. All it does is set up a table from the database and then returns the table.

I set the datasource within the same method as the initializeComponent (so my listbox will load with the existing data):

public Settings()
    {
        InitializeComponent();
        listBoxDays.DataSource = DBQuery.informationRetreval().DefaultView;
    }

When the user adds more data: I call a method in which I add the data to the database and then I call:

    listBoxDays.Refresh(); //update listbox

The Problem: This does not update the listbox. Upon initialization of my listbox the data will populate but after it will not change (hence refresh does not work). Why is that? I could set the DataSource again but that feels sloppy. After looking into some of the documentation I noticed the event handler DataSourceChanged which maybe more for what I am looking for. Nevertheless why wouldn't refresh work?

Thank you for your patience. Please let me know if I need to be more clear.


回答1:


Refresh(): Forces the control to invalidate its client area and immediately redraw itself and any child controls.

Refresh will not rebind your control, it will just cause the control to be redrawn. You will have to set the DataSource again with

listBoxDays.DataSource = DBQuery.informationRetreval().DefaultView;

and re-bind it.

Source: Microsoft MSDN




回答2:


It'll only refresh when objects have changed (ex. a different query), not the data. You can do this:

listBoxDays.DataSource = null;
listBoxDays.DataSource = DBQuery.informationRetreval().DefaultView;

to refresh it... everytime you need to.



来源:https://stackoverflow.com/questions/14969650/listbox-has-set-datasource-but-refresh-does-nothing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!