Category Archives: ASP.NET

Application_Error and asmx Web Services

I just found out after tracking down a weird popup alert error “Object reference not set to an instance of an object” that it was being caused inside an ASP.NET asmx web service being called from a ComponentArt grid control.  The web service was causing an exception but it was not caught by Application_Error!

I spent a few hours trying to find out where on the client the exception was occurring before tracking it to the web service.  I figured nothing was happening on the server since Application_Error didn’t log the error for me.

So, unless you know something I don’t know, make sure you add your own error handling to your Web Services.

How to Handle Null Values in a TemplateField ItemTemplate

I’ve been working on some ASP.NET projects lately and encountered something that was easy to solve, and should have been obvious straight off.

I was using a GridView to display some values including some columns that show dates. To edit the dates I wanted to use some controls from the AJAX Control Toolkit, specifically the MaskedEdit to format the input and the pop up Calendar control, so I had to use a TemplateColumn in the GridView and setup the EditTemplate with these controls.

I also wanted to format the date inside of the ItemTemplate to match the format of the other date BoundFields.

Even in ASP.NET 2.0 this was pretty easy, I just setup the template as follows:

<ItemTemplate>
<%# // If DueDate is null returns an empty string, otherwise formats and displays the date properly.
(null == Eval("DueDate")) ? string.Empty : DateTime.Parse(Eval("DueDate").ToString()).ToString("yyyy/MMM/dd") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="DueDate" runat="server" Text='<%# Eval("DueDate") %>' />
<tk:CalendarExtender ID="DueDateCalendar" runat="server" SkinID="Calendar" TargetControlID="DueDate" />
<tk:TextBoxWatermarkExtender ID="DueDateWatermark" runat="server" SkinID="DateWatermark" TargetControlID="DueDate" />
<tk:MaskedEditExtender ID="DueDateMaskedEdit" runat="server" SkinID="DateMask" TargetControlID="DueDate" />
</EditItemTemplate>

The biggest thing was checking for null in the Eval statement for the ItemTemplate. I also setup the ObjectDataSource to ConvertEmptyStringsToNull.

LINQ to SQL: The Most Powerful .NET Feature Since C# Attributes

Today I was reading Scott Guthrie’s blog post about the LINQ to SQL. IMHO LINQ looks like the best tool for .NET since C# Attributes! Since the .NET LINQ to SQL Designer will compile a database context for you we’ll never have to write stupid unit tests just to check if a query works (note: I said stupid unit tests). You’ll know the query works by the old programming myth “Well it must work, it compiled!”. Obviously we’ll still have to test some queries, but you know what I mean. You change a column name or drop a column from a table and sometimes you don’t know what parts of the application you broke until either your unit test fails, or if your unit test wasn’t explicit and specific enough, when your customer complains that the report isn’t working anymore.

Ever since Ruby on Rails came out and I actually learned it I lost my enchantment with ASP.NET – until now. Ruby on Rails still blows my mind with how easy it is to use, but I’m really happy that .NET now includes the AJAX framework and this excellent query tool.

The only thing I want from .NET now is Database Migrations in C# a la Ruby on Rails.

Creating a Custom ASP.NET Control with Postback OnClick Event

Note: I’ve been meaning to post this article since September but it is getting too complicated. I’ll include some more info in a future article. Maybe I’ll even make this a series on making custom controls that postback.
I recently had to create a new ASP.NET control that contained a couple of images and a link. Sometimes I wanted it to postback when clicked, and sometimes I wanted it to run a script, and sometimes I wanted it to run a script and then postback. Sounds funny, but it is true. This was a toolbar button control I wanted to create and make it look like one of those Outlook buttons.

I’ll spare you most of the details in what I did, but in the end the way I designed the control I wanted to put an onclick event onto a span that wrapped the other parts of the control (images and text controls). There are two important methods for getting a postback:

  1. ClientScriptManager.GetPostBackClientHyperlink()
  2. ClientScriptManager.GetPostBackEventReference()

The ClientScriptManager is available as an instance property of the Page class, including Control.Page as Page.ClientScript.

ClientScriptManager.GetPostBackClientHyperlink()

This method returns javascript:__doPostBack() as a string. It is suitable for using in an anchor href or onclick event handler. Unfortunately it prepends the javascript: to the front of the string, which is kind of ugly, but also makes it hard to use if you wanted to do a more complicated function. Because I wanted to be able to call client-side scripts before doing the post-back it was unusable for me.

ClientScriptManager.GetPostBackEventReference()

This method takes several parameters, including the names of an EventArgument, a ValidationGroup, and other goodies like tracking control focus between postbacks. The method returned is WebForm_DoPostBackWithOptions(), and also does not include the javascript: that GetPostBackClientHyperLink() gives you.

To make GetPostBackEventReference() work your control must implement the IPostBackEventHandler (and that is easy). Use IPostBackEventHandler.RaisePostBackEvent(string eventArgument) and switch on the eventArgument to define the server-side behaviour. For example, I passed “clicked” as the eventArgument to GetPostBackEventReference() so my RaisePostBackEvent() looks something like this:

void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
{
switch (eventArgument)
{
case EVENTARGUMENT_CLICK:
this.FireOnClick();
break;

default:
break;
}
}

The FireOnClick() method fires the Click EventHandler.

Conclusion

Its easy to get the Client-Script to Postback using the GetPostBackEventReference() method.

In my next article I’ll describe how to execute your own Client-Side OnClick event before posting back to the server.

ASP.NET CheckBoxList DataBinding with Checked

So today I ran into an interesting issue with DataBinding to a CheckBoxList in ASP.NET 2.0; you cannot bind the checked state to the checked boxes. You can bind the Value and Text, but not the Checked state.

This leaves you with a few options for setting the checked state after databinding:

  1. Manually build the ListItem Collection for the CheckBoxList, setting the Value, Text and Selected values instead of databinding.
  2. Loop through the Items collection after databinding checking for each item.
  3. There is no number 3.

I decided to manually build a ListItem collection as follows:

foreach (DataRow dataRow in dataTable) {
string text =
Convert.ToString(dataRow[COLUMN_TEXT]);
string value = Convert.ToString(dataRow[COLUMN_VALUE]);
bool selected = Convert.ToBoolean(dataRow[COLUMN_SELECTED]);
ListItem newListItem = new ListItem();
newListItem.Text = text;
newListItem.Value = value;
newListItem.Selected = selected;
checkBoxListMyPreferencesShow.Items.AddRange(newListItem);
}