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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">


<title>Untitled Page</title>


<script language="javascript">


Function SetValue()


{


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


}


</script>


</head>


<body>


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


<div>


<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>


</div>


</form>


</body>


</html>


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")

Reference:

ReadOnly Textbox ViewState in .NET 2.0

blog comments powered by Disqus