How to set selectbox value by external code in blazor?

269 views Asked by At

I'm using TelerikDropDownList and i want to set selectbox value by external code (manually, without the user interface) by an event.

     <TelerikDropDownList Id="TelerikDropDownListId"
                          @bind-Value="@Model.Id"
                          Data="@DataDropDownList"
                          ValueField="Value"
                          TextField="Text"
                          @ref="TelerikDropDownListId"/>

     <button @onclick="ChangeSelectBoxValue" />

     @code {

         public List<DropDownItem<long>> DataDropDownList = new List<DropDownItem<long>>();

         private void ChangeSelectBoxValue()
         {
             DataDropDownList.Add(new DropDownItem<long>() { Value = 0, Text = "(New)" });

             TelerikDropDownListId.TextField = "(New)";
             TelerikDropDownListId.Value = 0;

             StateHasChanged();
        }
     }

1

There are 1 answers

0
Vencovsky On

You need to add the new item in the list, but change the value that you pass in @bind-Value and not changing the value of the component ref.

private void ChangeSelectBoxValue()
{
    // add new item to the drop down list
    DataDropDownList.Add(new DropDownItem<long>() { Value = 0, Text = "(New)" });

    // change the value of the drop down
    Model.Id = 0; // same Value as the item added in the drop down list

    StateHasChanged();
}