Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

This is my ascx page(Visual WebPart):

<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<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

listName.Add(item.Name);

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 =
                @"<Where>
                             <Eq>
                             <FieldRef Name='FileLeafRef' />
                             <Value Type='Text'>my.docx</Value>
                             </Eq>
                             </Where>";
                SPListItemCollection collection = list.GetItems(query);
                foreach (SPListItem item in collection)
                {
                    string h = item.Name.ToString();
                    Response.Write(h);
                    //listName.Add(item.Name);
                }
                DropDownList1.DataSource = listName;
                DropDownList1.DataBind();
            }
}
share|improve this question
    
Any ideas? Cheers –  naijacoder May 24 '12 at 14:19

1 Answer 1

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

 
discard

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.