Selecting unique values in a Drop-down list using the Data View Web Part

I posted awhile ago about how to select unique values for tabular data views, but I have now received a few emails asking how to do it for drop-down lists. It is almost the exact same code, but apparently this is confusing enough to warrant a different post.

My code sample assumes you are using the default Announcements list on SharePoint and that the Title field is what you want to display.

First, browse out to your Announcements list (which you get by default when you create a SharePoint site), and add a few Announcements all with the same title (just for demonstrations sake :-))

Then...

1. Insert a Data View Web Part based on the Announcements list
2. Click Data..Style and change to the drop-down view style..OK
2. Probably best to switch to code view at this point
3. Find the code that looks like this:
<xsl:template name="dvt_1.body" xmlns:ddwrt="https://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:xsl="https://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<xsl:param name="Rows"/>
<xsl:param name="FirstRow"/>
<xsl:param name="LastRow"/>
<xsl:for-each select="$Rows">
<xsl:variable name="KeepItemsTogether" select="false()"/>
<xsl:variable name="HideGroupDetail" select="false()"/>
<xsl:variable name="GroupStyle" select="'auto'"/>
<xsl:if test="(position() &gt;= $FirstRow and position() &lt;= $LastRow) or $KeepItemsTogether">
<xsl:if test="not($HideGroupDetail)" ddwrt:cf_ignore="1">
<option style="display:{$GroupStyle}">
<xsl:value-of select="@Title"/>
</option>
</xsl:if>
</xsl:if>
</xsl:for-each>
</xsl:template>
4. Change that code to look like this:
<xsl:template name="dvt_1.body" xmlns:ddwrt="https://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:xsl="https://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<xsl:param name="Rows"/>
<xsl:param name="FirstRow"/>
<xsl:param name="LastRow"/>
<xsl:for-each select="$Rows">
<xsl:variable name="KeepItemsTogether" select="false()"/>
<xsl:variable name="HideGroupDetail" select="false()"/>
<xsl:variable name="GroupStyle" select="'auto'"/>

<!-- this next line is used to store the value we need to compare for uniqueness -->
<xsl:variable name="uniqueTitle" select="@Title"/>
<xsl:if test="(position() &gt;= $FirstRow and position() &lt;= $LastRow) or $KeepItemsTogether">
<xsl:if test="not($HideGroupDetail)" ddwrt:cf_ignore="1">
<!-- this next part is where we compare the variable created above to the current selection and if they are different, we write the value -->
<xsl:if test="@ID=//Rows/Row[@Title=$uniqueTitle][1]/@ID">
<option style="display:{$GroupStyle}" value="{@Title}">
<xsl:value-of select="@Title"/>
</option></xsl:if>
</xsl:if>
</xsl:if>
</xsl:for-each>
</xsl:template>
5. Save the page. Notice that only the unique values are displayed. You can use this code in any number of places in the XSLT (for example, inside a drop-down menu).