Danish Kp Danish Kp - 1 year ago 87
C# Question

Change Label.Text on it's own click event during Runtime?

All i need is a field that can be renamed by users as they wish by just clicking on it, i am using a label as the control here, when ever user click on it user could be able to enter text in the label and when he click outside of the label that enter text would be saved as the label text.

enter image description here

Answer Source

This is a quick solution:

private void label1_Click(object sender, EventArgs e)
    TextBox tb = null;
    if (label1.Controls.Count > 0)  // do we already have created our TextBox?
        tb = ((TextBox)label1.Controls[0]);  // yes. set reference.
        // is it already visible? we got clicked from outside, so we hide it:
        if (tb.Visible) { label1.Text = tb.Text; tb.Hide(); return; };
    else if (sender == null) return;  // clicked from outside: do nothing
         else  // we need to create the textbox
           tb = new TextBox();
           tb.Parent = label1;     // add it to the label's Controls collection
           tb.Size = label1.Size;  // size it
           // set the event that ends editing when focus goes elsewhere:
           tb.LostFocus += (ss, ee) =>   { label1.Text = tb.Text; tb.Hide(); };

    tb.Text = label1.Text;  // get current text
    tb.Show();              // display the textbox in place

It embeds a TextBox into the Label. Style the Label to be big enough for the expected user entry!

It expects no other controls to be embedded there.

If you need it more than once consider creating a custom editable label from this code!

Note that to work you need to click at a spot where focus can go, not just the empty space around. To remedy that you could code the Click event for the surrounding space, maybe like this:

private void unClickLabel(object sender, EventArgs e) {label1_Click(null, null);}

In the form constructor add this to all the 'outside' controls that won't take focus, like the Form or a TabPage or a PicureBox or a Panel:

public Form1()
   this.Click += unClickLabel;   
   tabPage1.Click += unClickLabel;   
   pictureBox1.Click += unClickLabel;

Note that the new Label text will not persist program runs! To allow that you need to store it in some outside user settings and load them at startup..

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download