0
votes

I have a textbox in my C# Winform. The program assigns a value to the textbox by default.

I want the user to have a right click function to edit this text at runtime. So when the user right click to edit, the backgroud should become white and user should be able to edit the text. And after editing, the background should return to default and non editable

I have created a ContextMenuStrip with right click event to edit text as follows and assigned readonly property to false when user right clicks and press edit menu item:

private void editTextToolStripMenuItem_Click(object sender, EventArgs e)
{
    itxt_CommonTitle.ReadOnly = false;
}

I am not sure how to proceed further. Is this possible using textbox?

2
You should set ShortcutsEnabled to false.Reza Aghaei
Are you saying just want the text box to become editable immediately on right-click, without the menu?Brian Rogers
No... Make it editable only by menu item. I already made it editable. But how do i change backgroud during edit and return to default after that?blackfury
When do you finish editing?Reza Aghaei
When i click outside of the textbox or anywhere on the winform. Make it editable only upon contextmenustrip itemblackfury

2 Answers

1
votes

I think you are missing a process. After edit, there should be an update or save method.

  1. textbox readonly = true;
  2. edit textbox: textbox readonly = false;
  3. button save: textbox readonyl = true;

Edit: Something like this:

    private void buttonSave_Click(object sender, EventArgs e)
    {
        textBox1.ReadOnly = true;
    }

    private void editToolStripMenuItem_Click(object sender, EventArgs e)
    {
        textBox1.ReadOnly = false;
    }

You dont need to change backColor, just readonly prop is fine.

1
votes

If you have not changed the BackColor of the TextBox in the designer then the background color should automatically change from white to gray when you set ReadOnly = true and change from gray back to white when you set ReadOnly = false. However, if you have changed it to something else in the designer, then the easiest way is just to set a private variable to remember the original BackColor before you enable the control for editing. Then you can restore the color after you set it back to read-only.

private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
    MakeTextBoxEditable(itxt_CommonTitle);
}

private void itxt_CommonTitle_Leave(object sender, EventArgs e)
{
    MakeTextBoxReadOnly(itxt_CommonTitle);
}

private void Form1_Click(object sender, EventArgs e)
{
    MakeTextBoxReadOnly(itxt_CommonTitle);
}


private Color origTextBoxBackColor = SystemColors.Control;

private void MakeTextBoxEditable(TextBox textBox)
{
    origTextBoxBackColor = textBox.BackColor;
    textBox.ReadOnly = false;
    textBox.BackColor = Color.White;
    textBox.Focus();
}

private void MakeTextBoxReadOnly(TextBox textBox)
{
    textBox.ReadOnly = true;
    textBox.BackColor = origTextBoxBackColor;
}