Question

I'm trying to add a ListViewItem to an existing ListView during Runtime.

I have a Client object that is created inside the UI and comunicates with the server, and so I need the UI to update whenever the server notifies the client of some state alteration.

I've used delegates/events to communicate between both, the thing is I can't seem to update the UI status even though everything else is communicating well.

I find it especially weird that I can do it with the exact same code if I put a button in the UI that, when clicked, adds a ListViewItem to the very same ListView.

I've checked the data received and the ListViewItem created by the code and everything is well, except that the program gets stuck when it gets to the part where the LVI should be added to the LV.

Here goes some related code:

    public delegate void MyEventHandler(string uname, bool function);

    public partial Class ClientWindow: Form{

    public Client c;

        public ClientWindow() {

                c = new Client();
                c.notifyUI += new MyEventHandler(HandleSomethingHappened);
                InitializeComponent();
                initListView();
            }


                (...)

        void HandleSomethingHappened(string foo, bool op) {

           if (foo != c.username && op) {
               ListViewItem listViewItem = new ListViewItem(foo);
               listOnlineUsers.Items.Add(listViewItem);
           }
           else
               removeUserFromUL(foo);}

        }
}


[Serializable]
public class Client : MarshalByRefObject, IClient {
    public event MyEventHandler notifyUI;

(...)

void NotifyUI(string uname, bool op) {
        Console.WriteLine("notifying");
        if (notifyUI != null) {
            Console.WriteLine("not null");

            Delegate[] invkList = notifyUI.GetInvocationList();

            foreach (MyEventHandler handler in invkList) {
                try {
                    IAsyncResult ar = handler.BeginInvoke(uname, op, null, null);
                    Console.WriteLine("Invoking event handler");
                }
                catch (Exception e) {
                    notifyUI -= handler;
                }
            }
        }
}

Any help will be appreciated, since I can see absolutely no reason for it not to work.

It might be something stupid I'm missing though.

Was it helpful?

Solution

in WPF I would use Dispathcer.Invoke(()=>{/*update UI here*/});

but in win forms I believe it is just ListViewItem.Invoke(somedelgate,params);

msdn for invoke

here is another resource http://www.codeproject.com/Articles/17688/Updating-the-GUI-from-another-thread-made-easy

the only reason I am thinking you are on a seperate thread is because you have IAsyncResult involved.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top