1

I am currently trying too develop a visual webpart for an on premise SharePoint environment. The webpart contains a dropdown which I need to set the text and value so that I can use this later as part of some CAML query.

Currently my code looks like this:

using (SPWeb web = new SPSite(siteurl).OpenWeb(weburl))
        {
            SPList list = web.Lists.TryGetList("MyList");
            SPQuery query = new SPQuery();
            query.Query = "<OrderBy><FieldRef Name='ID' Ascending='TRUE' /></OrderBy>";
            SPListItemCollection collection = list.GetItems(query);

            foreach (SPListItem item in collection)
            {
                MyDropdown.Items.Add(new ListItem { item.Title, item.ID.ToString() });

            }

        }

I have tried a few different ways of getting this to work however I am getting an error message saying:

The best overloaded method match for 'System.Web.UI.WebControls.ListItemCollection.Add(System.Web.UI.WebControls.ListItem)' has some invalid arguments

Any help on how I can achieve this or what I am doing wrong would be greatly appreciated.

1 Answer 1

3

Try the following:

using (SPWeb web = new SPSite(siteurl).OpenWeb(weburl))
    {
        SPList list = web.Lists.TryGetList("MyList");
        SPQuery query = new SPQuery();
        query.Query = "<OrderBy><FieldRef Name='ID' Ascending='TRUE' /></OrderBy>";
        SPListItemCollection collection = list.GetItems(query);

        MyDropdown.Datasource = collection;
        MyDropdown.DataTextField = "Title";
        MyDropdown.DataValueField = "ID";
        MyDropdown.DataBind();

    }
0

Your Answer

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

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