Thread safe way to update UI elements in C#

person Jason Huangfolder_openC#, Codelocal_offer, , access_time February 23, 2010
//declare the delegate
delegate void SetControlValueCallback(Control oControl, string propName, object propValue);
 
// the function that sets properties on the UI control
        private void SetControlPropertyValue(Control oControl, string propName, object propValue)
        {
            if (oControl.InvokeRequired)
            {
                SetControlValueCallback d = new SetControlValueCallback(SetControlPropertyValue);
                oControl.Invoke(d, new object[] { oControl, propName, propValue });
            }
            else
            {
                Type t = oControl.GetType();
                System.Reflection.PropertyInfo[] props = t.GetProperties();
                foreach (System.Reflection.PropertyInfo p in props)
                {
                    if (p.Name.ToUpper() == propName.ToUpper())
                    {
                        p.SetValue(oControl, propValue, null);
                    }            
                }
            }
        }
 
//To use it
//for example statusLabel is a Label, set its property Text with the value msg (string)
        private void showStatusMessage(string msg)
        {
            SetControlPropertyValue(statusLabel, "Text", msg);
        }

Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>