I recently had a DropDownList being pre-populated from a database. I also wanted to insert "Select" at the top of the list and make it a required field. Googling this yielded much misinformation for what turned out to be pretty simple to solve in the end.

Say you have a DDL like this:

<asp:DropDownList id="testDDL" runat="server">
    <asp:ListItem Text="Select"></asp:ListItem>


If we try to populate this DropDownList from a database with the values 1,2 and 3, and then try and add a RequiredFieldValidator, that validator will not fire.

Some people resort to creating a CustomValidator and/or JavaScript here. This is not necessary. We need to take a step back here and re-phrase the problem: We already have data in our list in the shape of the "Select" item. We now want to append data from the database. A quick search of the MSDN documentation leads to the AppendDataBoundItems property for the DropDownList.

From the documentation: "The AppendDataBoundItems property allows you to add items to the ListControl object before data binding occurs. After data binding, the items collection contains both the items from the data source and the previously added items." The italics are mine...

We can use the InitialValue of the RequiredFieldValidator in conjunction with the AppendDataBoundItems property of the DropDownList to arrive at a working solution:

<asp:DropDownList id="testDDL" AppendDataBoundItems="true" runat="server">
    <asp:ListItem Text="Select"></asp:ListItem>
<asp:RequiredFieldValidator ID="salaryReqVal" ControlToValidate="salaryDDL"
    ErrorMessage="*" Display="dynamic" InitialValue="Select"

Google Search == Internet Search

by admin 9. February 2009 10:56

I noticed a very interesting article from Jeff Atwood concerning the current state of play with respect to search engines. He makes the point that there really is no competition today when it comes to search engines; Google rules the roost.

Although I feel as Jeff does, that Google has truly earned its position, such a "monopoly" is surely a cause for concern? So, I decided to look a little closer at the statistics for the search engines driving traffic to this blog. Here are the results over a random time period:

VSeWSS 1.3


From the stats, it seems I am getting 32X times the traffic from Google as from the nearest competing search engine. It would seem that I better speak nicely of Google? If this was Microsoft's search engine, the wooly hat brigade would be screaming it from the rafters... hypocrisy is alive and well ;-)

kick it on DotNetKicks.com



PostIt Man This part will continue on with the new Web Part project we just created with VS 2008 and VSeWSS 1.3. The original plan was to implement a custom security access policy so that we could safely run our Web Part and read from an XML file. But like all good plans... For the purposes of this sample, we can simply up the trust level in the config file until we are confident that we have our Web Part functioning correctly. I may come back to the topic of CAS customization.

I recently created some Web Parts using version 1.2 of the extensions in combination with the command line. Typically, I would use the GAC for development. My testing cycle would then consist of building, uninstalling old version from GAC, deploying Feature, installing new version in GAC, and running IIS reset. This time around, I was unfamiliar with the extent to which 1.3 was going to automate things. For example, while creating this project, I did not have to use the command line once. The ultimate goal for this part is to actually get a Web Part working, using the new version of VSeWSS 1.3.

Although not necessary for the purposes of this tutorial, it helps to understand the development cycle of Web Part created as a Feature. If you were doing this manually, you would typically build it, deploy (copy) it, install it, activate the feature, and recycle the application pool. When updating code and redeploying, don't forget to deactivate the Feature first. Note also, that when we deactivate and uninstall a Feature, files such as CSS, images and the like, still remain on the file system. If you need to make changes to these with version 1.2, you may need to hand copy them. There is a config attribute for overwriting a file if it already exists, but I could never get this to work.

Back to business. Take a look at the XML below. Add the Addresses.xml file to the TestWebPart folder in Solution Explorer. We want to display some of this data in our Custom Web Part.

    <name>John Doe</name>
    <street>123 Some Street</street>
    <city>Some City</city>

    <name>Jane Doe</name>
    <street>456 Another Street</street>
    <city>Some Other City</city>


Here's the complete code from my Web Part. Note the use of the RunWithElevatedPrivileges delegate here. Without this, the code would run under the current user's permissions. This allows the code to run with the same permissions as SHAREPOINT\System.I also hand copied the Addresses xml file to the wpresources folder in my virtual directory as I had difficulty in correctly configuring my Feature to do this for me. Does anyone know the proper way to do this?

using System;
using System.Data;
using System.Runtime.InteropServices;
using System.Text;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace TestWebPart
    public class TestWebPart : System.Web.UI.WebControls.WebParts.WebPart
        DataSet ds;
        Label testLabel;

        public TestWebPart()

        protected override void CreateChildControls()

            // This following anonymous method allows a specified block of
            // code to run in the context of the SharePoint System Account
                // You must create a new SPSite object inside the delegate
                // because SPSite objects created outside do not have Full
                // Control even when referenced inside the delegate.
                using (SPSite site = new SPSite("http://" + System.Environment.MachineName))
                    string sUri
                        = site.WebApplication.IisSettings[SPUrlZone.Default].Path.FullName
                            + "\\wpresources\\Addresses.xml";
                    ds = new DataSet();

                    StringBuilder sb = new StringBuilder();
                    sb.Append(ds.Tables[0].Rows[0]["name"].ToString() + "," + "<br />");
                    sb.Append(ds.Tables[0].Rows[0]["street"].ToString() + "," + "<br />");
                    sb.Append(ds.Tables[0].Rows[0]["city"].ToString() + "," + "<br />");
                        + " " + ds.Tables[0].Rows[0]["zip"].ToString() + ".");

                    testLabel = new Label();
                    testLabel.Text = sb.ToString();



VS 2008 Tip: If like me, you often end up with a list of 'using' statements as long as your arm, try the following: Highlight all your 'using' statements, then, select Edit -> Intellisense -> Organize Usings -> Remove and Sort :-)

When you have your Web Part building successfully, do the following:

* Select Build -> Package Solution
* If you have already deployed, select Build -> Retract Solution
* Deploy Web Part

You may get the following error:

Security Error Message


To get around this, you need to open your AssemblyInfo.cs file (in the Properties folder) and add a System.Security.AllowPartiallyTrustedCallers assembly attribute. The framework will not by default allow an assembly that is not fully trusted to call another assembly that is not fully trusted. However, by adding this attribute we are telling the framework that it is okay to call other assemblies from this one. See below.

[assembly: AssemblyTitle("TestWebPart")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestWebPart")]
[assembly: AssemblyCopyright("Copyright © 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: System.Security.AllowPartiallyTrustedCallers]


Add Web Part


Upon redeployment, you may get the unexpected error page. If you check the event viewer Windows application log file, it should contain the following:

Request for the permission of type 'Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c' failed.

If you check the web.config file located in $Drive:\inetpub\wwwroot\wss\VirtualDirectories\80, and you will notice that VSeWSS had indeed added a safe entry for the Web Part:

  <SafeControl Assembly="TestWebPart, Version=, Culture=neutral,     PublicKeyToken=6bbd0bdca0a0fd9e" Namespace="TestWebPart"       TypeName="TestWebPart" Safe="True" />


It seems that when opting to deploy to the bin folder when creating the project, VSeWSS does just that and nothing more. VSeWSS still leaves the security options to us, which is the correct behaviour one would expect. By default, SharePoint Web applications are only allowed to run with a very restrictive trust level of WSS_Minimal. If we want to have our Web Part deployed to the bin folder, then in order for it to run we must do one of two things: either set the trust level to WSS_Medium or WSS_Full in the web.config, or create a custom CAS policy that will allow this assembly's managed code to run. We will up the level to WSS_Full here. In a production environment, you will need to make an informed decision on this yourself.

With the trust level updated, bear in mind that there may be other errors waiting for us. To view meaningful error messages in the browser rather than the unhelpful 'unexpected error' page, update the following in the web.config file:

* customErrors=off
* Enable Stack Traces by adding CallStack=”true” to the SafeMode tag
* Set the compilation debug attribute to "true"

You should now be able to view the Web Part. If you can't, I take no responsibility ;-)

Custom Web Part


If you decide to implement your own code access security policy, then this should be of help.

Update - 06-19-2007:
The following code from above does not play nice when deployed to a different machine:

using (SPSite site = new SPSite("http://" + System.Environment.MachineName))
{ ... }

Change it to the following:

using (SPSite site = new SPSite("http://" + HttpContext.Current.Server.MachineName.Trim().ToLower())) { ... }

kick it on DotNetKicks.com   411ASP.NET