none
Setting Value For LookUps and Option Set Through C# Code in CRM 2011

    Question

  • Hi,

    Can anybody tell me how to set the LookUp and Option Set Value through the Code Behind ? I was using the Early bound class concept using the Organization Service for accessing the CRM data and I was Trying to create a Record. But I dont know how to set the LookUp and Option set value for the form ?

    Deepak

     

    Thursday, February 17, 2011 11:06 AM

Answers

  • Hi Deepak,

    Take a look at this:

    http://social.msdn.microsoft.com/Forums/en-US/crmdevelopment/thread/dcc4f2d6-20e7-4a5c-abad-370083eb7f6c

    The code I suggest:

    //First is created a new contact

    Entity contact = new Entity("contact");
    contact.Attributes["firstname"] = "ContactFirstName";
    contact.Attributes["lastname"] = "ContactLastName";
    Guid contactId = _orgService.Create(contact, null);

    //Then assign the contact to an account.

     Entity account = new Entity("account");
    account["name"] = "Test Account1";
    EntityReference primaryContactId = new EntityReference("contact", contactId);
    account["primarycontactid"] = primaryContactId;

    Cheers.


    Ricardo Barona CRM Consultant
    Thursday, February 17, 2011 4:30 PM

All replies

  • Hello Deepak,

    Here's an example of how to set a lookup value programmatically, using CRM SDK in C#: http://ronaldlemmen.blogspot.com/2007/02/set-lookup-to-null.html


    Cornel Croitoriu - Senior Software Developer - www.Biz-Forward.com | www.Croitoriu.NET
    Thursday, February 17, 2011 2:51 PM
  • Hi Deepak,

    Take a look at this:

    http://social.msdn.microsoft.com/Forums/en-US/crmdevelopment/thread/dcc4f2d6-20e7-4a5c-abad-370083eb7f6c

    The code I suggest:

    //First is created a new contact

    Entity contact = new Entity("contact");
    contact.Attributes["firstname"] = "ContactFirstName";
    contact.Attributes["lastname"] = "ContactLastName";
    Guid contactId = _orgService.Create(contact, null);

    //Then assign the contact to an account.

     Entity account = new Entity("account");
    account["name"] = "Test Account1";
    EntityReference primaryContactId = new EntityReference("contact", contactId);
    account["primarycontactid"] = primaryContactId;

    Cheers.


    Ricardo Barona CRM Consultant
    Thursday, February 17, 2011 4:30 PM
  • Hi Ricardo,

     

    Thanks For your Reply. Anyways I figured out the Syntax for the Lookup and the Picklist. Anyways your link is very helpful.

     

    Thanks 

    Deepak 

    Friday, February 18, 2011 1:19 PM
  • Hi Cornel,

    I think your post link was related to CRM 4.0 Anyways I got the code for CRM 2011..

    Thanks

    Deepak

     

     

    Friday, February 18, 2011 1:20 PM
  • How did you set the Picklist/Optionset to a different value?
    Ivan
    Wednesday, March 02, 2011 7:36 PM
  •     // Option value 2 represents (Lead Source = Mailing List)
        Lead lead = new Lead { Subject = "Mailing List", LeadSourceCode = new OptionSetValue(1), FirstName = firstName, LastName = lastName, CompanyName = company, EMailAddress1 = email };
        Context.AddToLeadSet(lead);
    
        SaveChangesResultCollection saveResultCollection = Context.SaveChanges();
    

    Islam Eldemery
    http://idemery.net
    idemery
    Wednesday, March 02, 2011 9:17 PM
  • hi,

    I am trying to put a if condition from a fetch xml to a option set. can you tell me how to get the value from OptionSet?

    eg:

     

     

                    string fetch2 = @"

                       <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>

                      <entity name='opportunity'>

                        <attribute name='name' />

                        <attribute name='customerid' />

                        <attribute name='statuscode' />

                        <attribute name='opportunityid' />

                        <order attribute='name' descending='false' />

                        <filter type='and'>

                          <condition attribute='opportunityid' operator='not-null' />

                          <condition attribute='statecode' operator='in'>

                            <value>0</value>

                            <value>1</value>

                          </condition>

                        </filter>

                        <link-entity name='account' from='accountid' to='customerid' alias='aa'>

                          <filter type='and'>

                            <condition attribute='telephone1' operator='eq' value='" + MobileCheck.Text + @"'  />

                          </filter>

                        </link-entity>

                      </entity>

                    </fetch>";

     

     RetrieveMultipleRequest efr = new RetrieveMultipleRequest()

                    {

                        Query = new FetchExpression(fetch2)

                    };

     

     

     

       EntityCollection entityResults = ((RetrieveMultipleResponse)_serviceProxy.Execute(efr)).EntityCollection;

      foreach (var c in entityResults.Entities)
                    {
     Response.Write("statecode:" + c.GetAttributeValue<string>("statecode"));
                       if (c.Attributes["statecode"].Equals("1"))
     {
                           Response.Write("statecode4:"+c.Attributes["statecode"]);//closed=4
     }

     

    I get an Error in line :Response.Write("statecode:" + c.GetAttributeValue<string>("statecode"));

    error: Unable to cast object of type 'Microsoft.Xrm.Sdk.OptionSetValue' to type 'System.String'. 

     

    Please tell me how can i get the values of the statecode which is a picklist.

     



    Tuesday, May 17, 2011 6:54 PM
  • Hi NimuVini,

    You can get the option set values from the entity metadata, the following code retrieves the metadata of the opportunity and extracts the option set.

      RetrieveEntityRequest EntityRequest = new RetrieveEntityRequest
      {
        EntityFilters = EntityFilters.Attributes,
        LogicalName = "opportunity"
      };
    
      RetrieveEntityResponse EntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(EntityRequest);
      Dictionary<int, string> optionSet = GetOptionSet(EntityResponse.EntityMetadata, "statecode", 1033);
    
    
    
        public Dictionary<int, string> GetOptionSet(EntityMetadata entityMetadata, string attributeName, int languageCode)
        {
          Dictionary<int, string> allOptions = new Dictionary<int, string>();
    
          AttributeMetadata attributeMetadata = entityMetadata.Attributes.Where(atr => atr.LogicalName == attributeName).FirstOrDefault();
          if (attributeMetadata == null)
          {
            return allOptions;
          }
    
          List<OptionMetadata> optionList = new List<OptionMetadata>();
    
          if (attributeMetadata is StatusAttributeMetadata)
          {
            optionList.AddRange(((StatusAttributeMetadata)attributeMetadata).OptionSet.Options.ToList());
          }
          else if (attributeMetadata is StateAttributeMetadata)
          {
            optionList.AddRange(((StateAttributeMetadata)attributeMetadata).OptionSet.Options.ToList());
          }
          else if (attributeMetadata is PicklistAttributeMetadata)
          {
            optionList.AddRange(((PicklistAttributeMetadata)attributeMetadata).OptionSet.Options.ToList());
          }
          
          string selectedOptionLabel = string.Empty;
    
          foreach (OptionMetadata oMD in optionList)
          {
            if (!oMD.Value.HasValue) continue;
    
            var label = oMD.Label.LocalizedLabels.Where(l => l.LanguageCode == languageCode).FirstOrDefault();
            if (label != null)
              allOptions.Add(oMD.Value.Value, label.Label);
            else
              allOptions.Add(oMD.Value.Value, oMD.Label.UserLocalizedLabel.Label);
          }
    
          return allOptions;
        }
    


    Islam Eldemery
    http://idemery.net
    idemery
    Wednesday, May 18, 2011 7:39 AM