We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

How to set SfMultiSelect Dropdown default values from a database?

Hello,

I would like to understand how I can set the default values of a checkbox multiselect dropdown component using a value retrieved from a database column. I understand that this is possible to do by hard coding the values like this:

public int?[] EmployeeValue { get; set; } = { 1, 2 };

My column values are delivered as a string, however, the actual value needed is an int. Some examples of returned values would be: 1 OR 1, 2 OR 1, 2, 3 ,etc. I can split the values if needed, but I'm not clear on how to deliver them to the array.

What I functionally need is this: 

string x = "1, 2, 3" (result from db)

public int?[] EmployeeValue { get; set; } = { x };

This is obviously oversimplified; I wish it was that easy...

Thanks


1 Reply

UD UdhayaKumar Duraisamy Syncfusion Team January 16, 2023 01:02 PM UTC

To set the default values of a checkbox multiselect dropdown component using a value retrieved from a database column, you can use the following approach:


  1. Convert the string value retrieved from the database column into an array of integers using the string.Split method.
  2. Assign the array of integers to the EmployeeValue property of the MultiSelect component.
  3. This process can be done in the created event of the MultiSelect component.


Here's an example of how this can be implemented in code:


<div style="margin:100px auto;width:400px">

    <SfMultiSelect TValue="int[]" TItem="Country" Placeholder="e.g. Australia" Mode="VisualMode.CheckBox" @bind-Value="@ EmployeeValue " DataSource="@Countries">

        <MultiSelectEvents TItem="Country" TValue="int[]" Created="@CreatedHandler"></MultiSelectEvents>

        <MultiSelectFieldSettings Value="Code" Text="Name"></MultiSelectFieldSettings>

    </SfMultiSelect>

</div>

@code {

    public string x = "1, 2, 3";

 

    public int[]EmployeeValue { get; set; }

 

    private void CreatedHandler(Object args)

    {

        string[] DataBaseVlaue = x.Split(',');

        int[] values = Array.ConvertAll(DataBaseVlaue, int.Parse); //This will convert the string "1, 2, 3" into an array of integers {1, 2, 3}.

        EmployeeValue = values; //Assign the array of integers to the EmployeeValue property.

    }

}


Loader.
Up arrow icon