YouTip LogoYouTip

Prop Webcontrol Textbox Readonly

## ASP.NET TextBox ReadOnly Property The `ReadOnly` property is a member of the ASP.NET Web Server `TextBox` control. It is used to specify or determine whether the user can modify the text content inside the `TextBox` control. --- ## Definition and Usage The `ReadOnly` property accepts a Boolean value: * **`True`**: The text inside the `TextBox` is read-only. The user can see and highlight the text, but cannot modify it. * **`False`**: The text inside the `TextBox` can be modified by the user. This is the default value. Even when a `TextBox` is set to `ReadOnly="True"`, you can still programmatically change its text value in the server-side code-behind (e.g., C# or VB.NET). --- ## Syntax ```xml ``` --- ## Code Examples ### Declarative Example (ASPX Markup) The following example demonstrates how to set the `ReadOnly` property to `True` directly in your markup: ```xml
``` ### Programmatic Example (C# Code-Behind) You can also dynamically enable or disable the read-only state of a `TextBox` in your server-side code: ```csharp protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // Make the TextBox read-only programmatically tb1.ReadOnly = true; tb1.Text = "This text cannot be edited by the user."; } } ``` --- ## Key Considerations & Best Practices When working with the `ReadOnly` property in ASP.NET, keep the following behaviors in mind: ### 1. Postback Behavior and ViewState By default, if a `TextBox` is marked as `ReadOnly="True"`, any changes made to its value on the client side (via JavaScript) **will not** be posted back to the server. This is a security feature designed to prevent users from tampering with read-only data. If you need to modify a read-only value on the client side using JavaScript and have that value submitted to the server during a postback, you should: * Keep `ReadOnly="False"` on the ASP.NET control. * Add the HTML `readonly` attribute manually in your code-behind: ```csharp tb1.Attributes.Add("readonly", "readonly"); ``` ### 2. ReadOnly vs. Enabled It is important to distinguish between `ReadOnly` and `Enabled`: * **`ReadOnly="True"`**: The user cannot edit the text, but they can still click into the control, highlight the text, copy it, and the control participates in the tab order. * **`Enabled="False"`**: The control is completely grayed out. The user cannot click, focus, or select text inside it, and its value is not submitted during postbacks.
← Prop Webcontrol Textbox RowsProp Webcontrol Textbox Maxlen β†’