Domanda

I am currently trying to grab certain values(choice column) from a SP list into a DropdownList in Visual Studio, for example, currently in the SP List choice column, there're 5 choices altogether but I want to grab 3 out of the 5 choice and put it in a DropdownList in my Visual Studio form. Below is what I have tried so far with no success:

 protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            using (SPSite site = new SPSite("http://developmentserver.bwn"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["KPI Master"];
                    SPQuery query = new SPQuery();
                    query.Query = "<Where><Eq><FieldRef Name='CarType' /><Value Type='Choice'>KIA</Value></Eq></Where>";


                    SPListItemCollection Items = list.GetItems(query);

                    if (Items.Count > 0)
                    {

                        foreach (SPListItem Item in Items)
                        {
                            ddlDivision.DataSource = list.Items;
                            ddlDivision.DataBind();
                        }
                    } 
                }
            }

Can someone help an amateur SP Developer like me please?

Would really appreciate it.

È stato utile?

Soluzione

In your code, you don't need to add ddlDivision.DataBind(); inside foreach

foreach (SPListItem Item in Items)
      {
           ddlDivision.DataSource = list.Items;
           ddlDivision.DataBind();
      }

Try to loop for each item, then add it to the dropdown list as below

foreach (SPListItem Item in Items)
{
            ddlDivision.Items.Add(new ListItem(Item.Title));
}

The second option, try to remove foreach and set the data source for items

ddlDivision.DataSource = Items;
ddlDivision.DataTextField = "CarType";
ddlDivision.DataValueField = "CarType";
ddlDivision.DataBind();

If it's not working, Please, check

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange
scroll top