Monday 21 March 2011

Adding instance of WebUserControl to ASP.Net website project

It can easily be done using namespaces. Here's an example:




WebControl1.ascx:



Notice that Inherits references the namespace (MyUserControls), and not just the class name (WebControl1)



WebControl1.ascx.cs:



namespace MyUserControls { public partial class WebControl1 : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } } } Notice that the class have been included in the namespace MyUserControls



Default.aspx.cs:



using MyUserControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { var control = (WebControl1) Page.LoadControl("~/WebControl1.ascx"); } } This approach potentially allow you to redistribute your user controls (or keep them in a separate project) without the hassle of referencing them in your .aspx files.

Tuesday 1 March 2011

ASP.Net AJAX CalendarExtender - Get selected date from ReadOnly TextBox

In this article I will explain a very common issue faced while using the ASP.Net AJAX Control Toolkit CalendarExtender control.
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.

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 collections. 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];
}

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