Interview Questions administrator

Best SharePoint administrator Interview Questions and Answers with topic wise:


Recycle Bin | MMS | ManagedVsCrawledProperties |

Thursday, November 29, 2012

SPFieldChoice to the dropdown list programatically:


  1. List Name: MyList
  2. Choice Field Name: MyChoiceField and the values are
    1. MyChoice1
    2. MyChoice2
    3.  MyChoice3
First example to set the SPChoice field default value as dropdown list default value.


          try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    SPWeb web = site.OpenWeb(SPContext.Current.Web.ID);
                    SPList liMyLists = web.Lists["MyList"];
                    SPFieldChoice fcTypes = (SPFieldChoice)       
                                                liMyLists.Fields["MyChoiceField"];
                    ddlChoiceField.DataSource = fcTypes.Choices;
                   //To set choice field default value as dropdown list default value.
                    ddlChoiceField.SelectedValue = fcTypes.DefaultValue; 
                    ddlChoiceField.DataBind();
            }
            catch (Exception ex)
            {
               //code
             }
OutPut:


Second example to set the “Select “value as dropdown list default value with required validation
      try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    SPWeb web = site.OpenWeb(SPContext.Current.Web.ID);
                    SPList liMyLists = web.Lists["MyList"];
                    SPFieldChoice fcTypes = (SPFieldChoice)       
                                                liMyLists.Fields["MyChoiceField"];
                    ddlChoiceField.DataSource = fcTypes.Choices;
                   //Commented below code to display “Select” as dropdown list first value.
                    //ddlChoiceField.SelectedValue = fcTypes.DefaultValue; 
                    ddlChoiceField.DataBind();

                  //To display “Select” as default value and to do required validation.
                    ListItem lstItem = new ListItem();
                    lstItem.Text = "----Select------";
                    lstItem.Value = string.Empty;
                    ddlChoiceField.Items.Insert(0, lstItem);
          }
            catch (Exception ex)
            {
               //code
             }

OutPut: 

1 comment:

  1. This is a nice article. I have a specific requirement. i need to create a web part that display the survey in a small box which is 200 x 500 px. i have to mimic the submission of survey from any page. i was able to read and display the question and choices(answers correctly). do u know of any way i can save the selection. i saw the edit form and its too complicated code.

    ReplyDelete