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;
  • Any ideas? Cheers
    – naijacoder
    May 24, 2012 at 14:19

1 Answer 1


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>();

  • 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, 2012 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. May 29, 2012 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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