Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

http://i.stack.imgur.com/0NOlP.jpg

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

http://i.stack.imgur.com/3uX53.jpg

Thank you very much in advance.

like image 270
Vallar Avatar asked Feb 20 '23 19:02

Vallar


2 Answers

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)
}
like image 160
dtown123 Avatar answered Mar 07 '23 17:03

dtown123


If you want to update your label when the textbox change you should wire the TextChanged events of the textbox:

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

Set the event using the Form Designer or dinamically when you load your form.

like image 45
Steve Avatar answered Mar 07 '23 19:03

Steve