views:

288

answers:

6

Im using c#.net windows form application.I have a text box. How can I make the text box unselectable. I don't want to disable the complete textbos

A: 

Try using CanFocus property.

Andrew Bezzub
CanFocus is read-only. It's only there to indicate whether or not the control can receive focus.
Chris Schmich
+1  A: 

You have a couple of options:

  1. Use a Label control instead.
  2. Set textBox.Enabled = false to prevent selection (see here).
Chris Schmich
+3  A: 

You are going to need to explain more. Disabling, by definition, is making a control unselectable. Unless that control is something like a label, which isn't selectable to begin with, then the concept of "unselectable" but still a textbox are mutually exclusive.

For example, how do you plan to scroll the text in the textbox if you can't select it?

Mystere Man
A: 

Probably the best way is to put a label behind it, and when you want to make the textbox disabled, hide it and show the label in its place.

SLC
A: 

In the 'Enter' event of the textbox set the ActiveControl to something else:

    private void txtMyTextbox_Enter(object sender, EventArgs e)
    {
        ActiveControl = objMyOtherControl;
    }
HappyCoder4U
@Chris: Good option. However, switching with a label would work if he's not using a richtextbox (he did say "text box", though). Depending on the content, he might not be able to display it in a label.@Mystere Man: A textbox/richtextbox can be resized with code to fully accomodate the text.@Edglex: He said he's working with a Windows Form. Focusable is available in WPF, but not Windows Forms.
HappyCoder4U
A: 

@Mystere Man: You might want a text box that cannot be used all the time. For example, I allow the user to create text boxes on a canvas and drag them around. To prevent them from selecting and moving text when they are dragging I need to disallow user input, and text selection also needs to be disabled because it causes a delay which messes up my drag function. In my application the user can only edit a text box when he has double clicked on it, and must then click outside of the text box to be able to move it again.

I basically have this code (where t is a TextBox):

// Prevent text entry
t.IsReadOnly = true;

// Prevent text selection
t.Focusable = false;

This behaviour is preferable to disabling the whole control (t.Enabled = false), since that would also stop mousedown and doubleclick events, which would stop dragging and changing from edit to drag mode from working. Not to mention that the text box would go grey.

Edglex