Saturday, October 18, 2008

ReadOnly TextBox in ASP.NET

If you set the value of a readonly textbox via javascript, you cannot get the text property of the textbox from code behind. The solution is to use the Request object.

Here is how:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="TestTime._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >

<head runat="server">

<title>Untitled Page</title>

<script language="javascript">

Function SetValue()


document.getElementById("txtTest").value = "Test";





<form id="form1" runat="server">


<asp:TextBox ID="txtTest" runat="server" ReadOnly="true"></asp:TextBox>

<asp:Button ID="Button1" runat="server" Text="PostBack" OnClientClick="SetValue();"/>

<asp:Label ID="lblTest" runat="server"></asp:Label>





Partial Public Class _Default

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

lblTest.Text = txtTest.Text 'txtTest.Text = ""

lblTest.Text = Request(txtTest.ClientID) 'Request(txtTest.ClientID)= "Test"

End Sub

End Class

Optionally, you can use the following line to set the readonly attribute:

txtMyTextBox.Attributes.Add("readonly", "readonly")


ReadOnly Textbox ViewState in .NET 2.0

blog comments powered by Disqus