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:
- Get last modified time of a file in C#.Net
- Change authentication mode after installation of SQL Server
- alert() method examples in JavaScript
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!