Friday 2 November 2012

Dynamics CRM 2011 - How to set Optionset as datasource in Silverlight Combobox

In this post we will see how we can bind a Silverlight Combobox with values of a field of type CRM Optionset.
In the example the combobox is within a grid. The combobox code in the designer would be as given below:
The Designer :
<sdk:DataGridTemplateColumn Header="Category" Width="95" CellStyle="{StaticResource CRM2011_DataGridCellStyle}">

            <sdk:DataGridTemplateColumn.CellTemplate>

                <DataTemplate>

                    <TextBlock Text="{Binding Category}" />

                </DataTemplate>

            </sdk:DataGridTemplateColumn.CellTemplate>

            <sdk:DataGridTemplateColumn.CellEditingTemplate>

                <DataTemplate>

                    <ComboBox SelectedItem="{Binding Category, Mode=TwoWay}"                                 

                                      DisplayMemberPath="Value"

                                        SelectedValuePath="Key"                                                                       

                                  ItemsSource="{StaticResource CategoryListing}" Height="22" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"/>

                </DataTemplate>

            </sdk:DataGridTemplateColumn.CellEditingTemplate>

        </sdk:DataGridTemplateColumn>

In the above code the Static Resource CategoryListing is of type Dictionary. The Value is set as the DisplayMemberPath property and Key is set in the SelectedValuePath property.
In the example we have taken the ItemsSource as Static Resource .So in the codebehind the static resource should be assigned with values before InitializeComponent() is called.

The Model class :

ExpenseNoteModel is the class bound with the Datagrid.
The property “Category” is set in the SelectedItem property. The selected Item would normally display the value as “[key,value]” format where as we would like to display simply the value as selected item. To do so we have used string functions while setting and getting the Category. We set the key property while Set of Category . So we can use the key property of the model class to set selected value for a field.

public class ExpenseNoteModel : ink_expensenote

    {

        private string selectedCategory;

        private string returnValue;

        public string Category

        {

            get

            {

                if (String.IsNullOrEmpty(selectedCategory) == false)

                {

                    string[] category = selectedCategory.Split(',');

                    if (category.Length > 0)

                    {

 

                        returnValue = category[1].TrimEnd(']');

                    }

                }

                return returnValue;

            }

            set

            {

                selectedCategory = value;

                if (String.IsNullOrEmpty(selectedCategory) == false)

                {

                    string[] category = selectedCategory.Split(',');

                    if (category.Length > 0)

                    {

 

                        key = int.Parse(category[0].TrimStart('['));

                    }

                }

            }

        }

        public int key

        {

            get;

            set;

        }

        public Dictionary<int, string> Categories

        {

            get;

            set;

        }

    }

The codebehind:
The function below gets the Optionset labels and values and set them in a dictionary type object.

Dictionary<int,string> categoryListing=new Dictionary<int,string>();  

  

//Add the below lines in the Initialization method of your class

 

public ExpenseNotePage()

{

    this.Resources.Add("CategoryListing", categoryListing);

    GetOptionSetLabels();

    InitializeComponent();

}

 

 

  /// <summary>   

    /// Get options set labels for specified entity's optionset type attribute   

    /// </summary> 

    /// <param name="entityName"></param>   

    /// <param name="attributeName"></param>   

    private void GetOptionSetLabels()

    {

      try

      {

        OrganizationRequest request = new OrganizationRequest();

        request.RequestName = "RetrieveAttribute";

        request["EntityLogicalName"] = "ink_expensenote";

        request["LogicalName"] = "ink_category";

        request["MetadataId"] = Guid.Empty;

        request["RetrieveAsIfPublished"] = true;

        IOrganizationService service = SilverlightUtility.GetSoapService();

        service.BeginExecute(request, new AsyncCallback(OnGetOptionSetLabelsComplete), service);

      }

      catch (Exception ex)

      {

        throw ex;

      }

    }

 

 

 

 

    /// <summary>  

    /// Retrieve the results  

    /// </summary>  

    /// <param name="result"></param>  

    private void OnGetOptionSetLabelsComplete(IAsyncResult result)

    {

      //Get the original query back from the result.  

      OrganizationResponse response = ((IOrganizationService)result.AsyncState).EndExecute(result);

 

      if (response != null && response.Results.Count > 0)

      {

        //Get the actual optionset meta data  

        categories = ((EnumAttributeMetadata)(response.Results[0].Value)).OptionSet;

 

        for (int j = 0; j < categories.Options.Count; j++)

        {

          categoryListing.Add(int.Parse(categories.Options[j].Value.ToString()),categories.Options[j].Label.UserLocalizedLabel.Label.ToString());          

        }       

      }

    }

   

No comments:

Post a Comment