Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Tuesday, June 16, 2020

Get value of ReadOnly TextBox in ASP.Net and retain its value across PostBack

Here Sandeep Kumar Rauniyar has explained how to get the value of ReadOnly TextBox on PostBack and also how to retain its value across PostBacks.

In this article I will explain how to get the value of ReadOnly TextBox on PostBack and also how to retain its value across PostBacks.

 A common example is when working with Calendar Control, when date is selected the value is set client side and if the TextBox is set as ReadOnly the selected date value is lost and the updated value is not available in the TextBox Text property on PostBack.


Issue
Whenever for the ASP.Net Textbox if the ReadOnly property of the Textbox is set to true, the selected data is not available in the Text property of the Textbox on PostBack as shown in the screenshot below.
 



Reason
 
The reason behind this issue is that whenever value of an ASP.Net Textbox is set to ReadOnly and the value of the textbox is set client side using client side script like JavaScript, in such cases the value of the Textbox is not available in the Text property of the ASP.Net Textbox. The ASP.Net AJAX Control Toolkit CalendarExtender makes use of JavaScript to set the selected date in the Textbox.
 
Solution
 
The solution to the issue is making use of Request.Form collection. As this collection has values of all fields that are posted back to the server and also it has the values that are set using client side scripts like JavaScript.
 
Thus we need to do a small change in the way we are fetching the value server side.
 
C#
 
protected void Submit(object sender, EventArgs e)
{
    string date = Request.Form[txtDate.UniqueID];
}
 
VB.Net
 
Protected Sub Submit(ByVal sender As ObjectByVal e As System.EventArgs)
    Dim strDate As String = Request.Form(txtDate.UniqueID)
End Sub
 
As you can see above I am fetching the value of the Textbox from the Request.Form collection using the UniqueID property of the Textbox which is nothing but Client Side name of the ASP.Net TextBox control
The screenshot below describes that the selected date value is now available server side when fetched using the Request.Form collection
 




No comments:

Post a Comment