blackfury
blackfury

Reputation: 685

Allow user to edit label and change text - c# winform

I have a winform with a custom label inherited from a Windows Form Label. I need to allow user to edit this label and change the value.

I know we can use textbox to allow user to edit by changing the readonly property to false.

But the reason why i use label is that i might need to change the orientation of the text and hence the custom label.

So my question is, is it possible to allow user to edit a normal Winform Label?

The post: Editable Label Controls is not a working solution. That also doesn't have an accepted answer.

Upvotes: 0

Views: 2547

Answers (1)

Devon Mathews
Devon Mathews

Reputation: 55

This isn't the best option by far, however, it's still an option. Set your forms KeyPreview to true, add a KeyDown key event handler to your form and a Click event handler to your label. In the click event handler, have it set a bool to true. Inside the keydown handler, have an if statement that adds the keys pressed to the labels Text property if the bool is true, that way, if the user clicks the label then anything they type will go into the label.

Example code for my horrible description:

public static Form f1 = new Form();
public static Label l1 = new Label();
public static bool isLabelClicked = false;

Then put these in whatever method sets the properties for your form and it's objects.

f1.KeyPreview = true;
l1.Click += new EventHandler (l1_Clicked);
f1.KeyDown += new KeyEventHandler (f1_keydown);

Then have these two methods in your project

public static void l1_Clicked(object sender, EventArgs e)
{
    isLabelClicked = true;
}

public static void f1_keydown(object sender, KeyEventArgs e)
{
    if (isLabelClicked == true)
    {
        if (e.KeyCode == Keys.A)
        {
            l1.Text += "a";
        }
        else if (e.KeyCode == Keys.B)
        {
            //Etc. For each key
        }
    }
}

It's not the most efficient way to do it and you'd need to set a way to make the bool false afterwards so it didn't keep changing the Labels value every time you typed, but it would work.

I'm sure there's also an easier way to handle each different key without writing out a giant if, else if block, just be weary of converting KeyCode since "," can be "Oemcomma". Good luck with your coding :)

Upvotes: 4

Related Questions