How to change text in a textbox on another form in Visual C#?

后端 未结 7 2019
抹茶落季
抹茶落季 2020-12-02 01:30

In Visual C# when I click a button, I want to load another form. But before that form loads, I want to fill the textboxes with some text. I tried to put some commands to d

7条回答
  •  不知归路
    2020-12-02 01:39

    I know this was long time ago, but seems to be a pretty popular subject with many duplicate questions. Now I had a similar situation where I had a class that was called from other classes with many separate threads and I had to update one specific form from all these other threads. So creating a delegate event handler was the answer.

    The solution that worked for me:

    1. I created an event in the class I wanted to do the update on another form. (First of course I instantiated the form (called SubAsstToolTipWindow) in the class.)

    2. Then I used this event (ToolTipShow) to create an event handler on the form I wanted to update the label on. Worked like a charm.

    I used this description to devise my own code below in the class that does the update:

    public static class SubAsstToolTip
    {
        private static SubAsstToolTipWindow ttip = new SubAsstToolTipWindow();
        public delegate void ToolTipShowEventHandler();
        public static event ToolTipShowEventHandler ToolTipShow;
    
        public static void Show()
        {
            // This is a static boolean that I set here but is accessible from the form.
            Vars.MyToolTipIsOn = true; 
            if (ToolTipShow != null)
            {
                ToolTipShow();
            }
        }
    
        public static void Hide()
        {
            // This is a static boolean that I set here but is accessible from the form.
            Vars.MyToolTipIsOn = false;
            if (ToolTipShow != null)
            {
                ToolTipShow();
            }
        }
    }
    

    Then the code in my form that was updated:

    public partial class SubAsstToolTipWindow : Form
    {
        public SubAsstToolTipWindow()
        {
            InitializeComponent();
            // Right after initializing create the event handler that 
            // traps the event in the class
            SubAsstToolTip.ToolTipShow += SubAsstToolTip_ToolTipShow;
        }
    
        private void SubAsstToolTip_ToolTipShow()
        {
            if (Vars.MyToolTipIsOn) // This boolean is a static one that I set in the other class.
            {
                // Call other private method on the form or do whatever
                ShowToolTip(Vars.MyToolTipText, Vars.MyToolTipX, Vars.MyToolTipY);     
            }
            else
            {
                HideToolTip();
            }
    
        }
    

    I hope this helps many of you still running into the same situation.

提交回复
热议问题