Search code examples
c#winformstextboxlabel

How to dynamically update Label text when textbox changes


I am having a problem with updating the text of my label. Not sure how do I go about doing this.

I have a label (lable1) and a text box (secondTextBox)and I have a tree view that the user needs to select items from. The process goes like this:

User selects an element in the tree view, label1 displays default text and secondTextBox appears. When the user changes the default text inside secondTextBox the text inside label1 should automatically update itself without the user pressing anything (bear in mind that I have about 45 nodes that needs this to be active, is there a quick way to do this or do I have to edit the code for the 45 nodes?).

So far I was able to do the first change, however whenever the user enters anything, the label doesn't update automatically, the user has to select something else from the tree view and goes back to the original selection for the text to update.

Here is my code so far:

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
    {
        if (treeView1.SelectedNode.FullPath == @"Node0/Node1")
        {
            label1.Text = String.Format("Whatever default text there is {0}"
     textBox1.Text);
        }
     }
}

}

Here is the screen shot for when it is in default mode.

https://i.sstatic.net/0NOlP.jpg

Here is the screen shot for when I have entered text, but there is no change in the label box:

https://i.sstatic.net/3uX53.jpg

Thank you very much in advance.


Solution

  • It looks like you just need to add a TextChanged event handler to your textbox1 control. Try putting this in your Form1 constructor:

    textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
    

    Next, add this method:

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        label1.Text = String.Format("Whatever default text there is {0}", textBox1.Text)
    }