Powered by Blogger.

Sunday, February 16, 2014

Readonly textbox value lost on postback asp.net



In this post we will discuss how to retain values in readonly textbox on postback if it lost in Asp.net.

Also you can check my previous posts on:

- WCF tutorial and example in C#.Net

- Forms Authentication in Asp.Net

- User Defined Function example in SQL Server 2008

In my scenario I was setting some value to some textboxes using JavaScript on page load. And the textboxes are readonly textboxes.

I was setting the value like below:

<script type="text/jscript">
document.getElementById('ContentPlaceHolder1_txtHello').value = 'Hello World'
</script>

<asp:TextBox ID="txtHello" runat="server" ReadOnly="true"></asp:TextBox>
<asp:Button ID="btnGetValue" runat="server" Text="Cancel" OnClick="btnGetValue_Click" />

And on the button click event I want to retrieve the textbox value.

In the page load the value is setting properly but when I tried to get the value in the button click it was giving me "". And If I remove the ReadOnly attribute then I am able to get the value.

There are two approaches to retain the value for readonly textboxes.

1st Approach:
Instead of putting ReadOnly="true" Put  ContentEditable="false", this will work same as ReadOnly that is user will not able to modify the value. Now in the button click you will able to get the value.

2nd Approach:
Add the attribute in the Page_Load like below:

protected void Page_Load(object sender, EventArgs e)
{
     txtHello.Attributes.Add("readonly", "readonly");
}

After this line you will able to get the readonly textbox value in postback.

Hope this will be helpful to you!



0 comments

Post a Comment