This quick start guides you through the steps of adding the ComboBox control in your Blazor application, adding data to it and displaying the data in the control. In this example, we create a data source by creating a list of countries and bind the list to the control to display the names of countries in the control.
Example Title |
Copy Code
|
---|---|
<link rel="stylesheet" href="/_content/C1.Blazor.Core/styles.css" /> <link rel="stylesheet" href="/_content/C1.Blazor.Input/styles.css" /> |
HTML |
Copy Code
|
---|---|
<script src="/_content/C1.Blazor.Core/scripts.js"></script> <script src="/_content/C1.Blazor.Input/scripts.js"></script> |
Razor |
Copy Code
|
---|---|
@using C1.Blazor.Input |
In the Data folder, add a class, say Country, and add the following code.
C# |
Copy Code
|
---|---|
public class Country { public override string ToString() { return Name; } public string Code { get; set; } public string Name { get; set; } public static List<Country> GetCountries() { var assembly = typeof(Country).GetTypeInfo().Assembly; var stream = assembly.GetManifestResourceStream("ComboBox.Data.countries.json"); var json = new System.IO.StreamReader(stream).ReadToEnd(); var countries = JsonSerializer.Deserialize<Dictionary<string, string>>(json); var listContries = new List<Country>(); foreach (var item in countries) { listContries.Add(new Country() { Code = item.Key, Name = item.Value.ToString() }); } return listContries.OrderBy(c => c.Name).ToList(); } } } |
To bind ComboBox to data, set the ItemsSource property and type of the type parameter T for C1ComboBox component. Here, the ItemsSource property accepts the collection of items for the ComboBox control.
Replace the existing code in the Pages\Index.razor page with the following code.
Razor |
Copy Code
|
---|---|
<C1ComboBox ItemsSource="countries" T="Country" Text="Select a Country" /> @code { IEnumerable<Country> countries; protected override void OnInitialized() { countries = Country.GetCountries(); } } |