SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This is my ascx page(Visual WebPart):

<asp:DropDownList ID="DropDownList1" runat="server">
<asp:Button  runat="server" ID="btn" onclick="btn_Click" Text="submit"/>

As you can see when I print out the item name it works but when I do


I get error. It doesn't add the items to the dropdown

Any ideas what I'm doing wrong? Also can I use SPQuery to show all documents and not use the where clause?

 protected void btn_Click(object sender, EventArgs e)
             List<string> listName = null;

            string siteUrl = "http://site";
            using (SPSite spSite = new SPSite(siteUrl))
                SPList list = spSite.RootWeb.Lists["Shared Documents"];
                SPQuery query = new SPQuery();
                query.ViewFields = @"<FieldRef Name='FileLeafRef' />";
                query.Query =
                             <FieldRef Name='FileLeafRef' />
                             <Value Type='Text'>my.docx</Value>
                SPListItemCollection collection = list.GetItems(query);
                foreach (SPListItem item in collection)
                    string h = item.Name.ToString();
                DropDownList1.DataSource = listName;
share|improve this question
Any ideas? Cheers – naijacoder May 24 '12 at 14:19
up vote 1 down vote accepted

From the code snippet above it looks like you're never initializing your List<string> listName. It's still a null object. instead of List<string> listName = null, do List<string> listName = new List<string>();

share|improve this answer
Thanks Andrew i have reviewed the code and solved it. Just by doing DropDownList1.items.Add(item.Name) No need to databind also made sure to clear the DDL before adding items. Cheer – naijacoder May 28 '12 at 7:15
That would work as well since the DDL automatically initializes it's own collection of ListItems, ensuring that you aren't trying to add to a null object. – AndrewSwerlick May 29 '12 at 12:56

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.