Friday, 30 April 2010

VB.NET: Use a Ternary Operator to check variable before assignment

It's a nice thing to be able to quickly check a value before assigning it to a variable, perhaps in a situation where you want to avoid a NullReferenceException.

If you want to do this, you can use a Ternary Operator which allows you to do the whole thing on one line:

Dim s As String
s = If(Session("mySessionVar") Is Nothing, String.Empty, Session("mySessionVar").ToString)

For more detail, refer to this blog post.

Monday, 12 April 2010

ASP.NET: Reset Selected Value of AJAX Combo Box

I have been banging my head off my desk for hours and hours, trying to find a way to reset the value of an ASP.NET Control Toolkit Combo Box.

Fundamentally it's a brilliant control and lends some superb ease of use to an application when applied properly, but for some reason it's lacking a straightforward and functional way to reset its value to a default of something like:

<asp:ListItem Value="0"> -- Select -- </asp:ListItem>

I tried various combination of these, plus messing about with the AppendDataBoundItems property and the ViewState setting:

ComboBoxSelector.SelectedIndex = -1
ComboBoxSelector.SelectedIndex = 0

Those are not important, the thing to note is that using any of the above will not actually reset the value of the Combo Box.

To reset it, you have to loop through the hidden controls that are created at runtime, and reset those to the default value:

Dim ctl As Control
For Each ctl In ComboBoxAllKeywordCategories.Controls
If TypeOf ctl Is HiddenField Then
CType(ctl, HiddenField).Value = "0"
End If

This works, and resets the Combo back to the default value you want. I no longer feel the need to put my fist through my monitor, so, result.

Friday, 9 April 2010

ASP.NET: How to Group Data in the GridView Control

One of my clients was not happy with a GridView control that repeated a category name next to every product inside that category. He asked if we could group the table to display the category name only once rather than displaying it for every product, e.g. something like:

'Crap', I thought. 'This doesn't come easily to the GridView control.'

But after some research into several different methods, I found a good one that worked well for me. It was created by a developer called 'dotNetSoldier', and the control is called the ZNet Extended GridView.

You just download the DLL file and drop it into your bin folder, add the control to your Toolbox and drag it onto your page. Then follow the instructions on his blog to get started.

I'd rather not have had to add another reference in my project or use a third party control, but I couldn't get the traditional GridView to behave in this way.