Home > Blockchain >  How do I set the selected-value of a combo-box in Blazor?
How do I set the selected-value of a combo-box in Blazor?

Time:03-03

I've created a Blazor server app targeting .NET 6.0.

I then add a combo-box to the default Counter.razor page like this

<button  @onclick="IncrementCount">Click me</button>

<p>
    <label>
        Select a car:
        <select @onchange="SelectedCarsChanged" >
            <option value="">Select a car</option>
            <option value="audi">Audi</option>
            <option value="jeep">Jeep</option>
            <option value="opel">Opel</option>
            <option value="saab">Saab</option>
            <option value="volvo">Volvo</option>
        </select>
    </label>
</p>

Here's the @code section after the combo-box addition.

    private int currentCount = 0;
    private void IncrementCount()
    {
        currentCount  ;
    }
    string SelectedCar = "";
    void SelectedCarsChanged(ChangeEventArgs e)
    {
        if (e.Value is not null)
        {
            SelectedCar = (string)e.Value;
        }
    }

The user selects a car and then presses the "Click me" button.

How do I reset the combo-box to "Select a car" in the IncrementCount() routine when that happens?

CodePudding user response:

You are almost there, bind SelectedCar to select like this

 <select @bind=@SelectedCar>
            <option value="">Select a car</option>
            <option value="audi">Audi</option>
            <option value="jeep">Jeep</option>
            <option value="opel">Opel</option>
            <option value="saab">Saab</option>
            <option value="volvo">Volvo</option>
        </select>

And select SelectedCar like this

 private void IncrementCount()
    {
        currentCount  ;
        SelectedCar = "";
    }
  • Related