6

Here is my list with name "Department" and name,mobile these are my column name and i want to add to my dropdown list only mobile number(column)plz help me ...

    SPSite site = new SPSite("http://alluser/Staffs");
    SPWeb web = site.OpenWeb();
    SPList list = web.Lists["Department"];
    SPFieldChoice filed = (SPFieldChoice)list.Fields["mobile"];
    drop_dept.DataSource = filed.Choices;
    drop_dept.DataBind();

that code not showing any thing to my dropdownlist.... can any one gave me sol.

1

I used the same Code and it worked for me. Check your Choice Field I think You Might forgot to add Choices in your Choice Field.

I used Code from Shobha's Blog and it is also working.

1

you can try this:

        Guid siteId = SPContext.Current.Site.ID;
        SPSecurity.RunWithElevatedPrivileges(delegate()
         {
             using (SPSite site = new SPSite(siteId))
             {
                 using (SPWeb objSPWeb = site.RootWeb)
                 {
                     SPList objSPList = objSPWeb.Lists["Department"];

                     SPFieldChoice field = (SPFieldChoice)objSPList.Fields["mobile"];
                     DropDownList1.DataSource = field.Choices;
                     DropDownList1.DataBind();
                 }
             }
         });

very similar to yours, as i think yours work, maybe its the user your using? so iv wrapped it into a runwithelevatedpriv

hope it helps :)

  • 1
    I dont know why iv been marked down as its perfectly fine to wrap a spsecurity as the user the op could be using could not have access to the list that they want to get the mobile colum from! – Ali Jafer Dec 29 '12 at 11:03
  • if my answer is correct please mark it as correct so others know the answer two when they come up with the same issue :) thanks – Ali Jafer Dec 31 '12 at 23:38
1

I found that for some reason the following code:

drop_dept.DataSource = filed.Choices;
drop_dept.DataBind();

always makes drop_dept.SelectedItem refer to the first element on the list regardless the item actually selected.

Replacing it with:

foreach (string choice in filed.Choices)
{
    drop_dept.Items.Add(choice);
}

solved my problem.

1

Here is what I used for a solution for SP 2013 where IQSReportNames is my SharePoint list name and the title field (from that sharepoint list) is what goes into the drop down:

reportName = new DropDownList();

Guid siteId = SPContext.Current.Site.ID;
using (SPSite site = new SPSite(siteId))
{
     using (SPWeb web = site.OpenWeb())
     {
          SPList oList = web.Lists["IQSReportNames"];
          string url = string.Empty;
          foreach (SPListItem oItem in oList.Items)
          {
               reportName.Items.Add(new ListItem(oItem.Title));
          }
     }
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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