This is my combo box
<ComboBox
Name="truck_trypes_combo"
DisplayMemberPath="description"
SelectedValuePath="id"
Header="Truck category"
>
Am setting its itemsource via
TruckTypesSqlite truckypessqlite = new TruckTypesSqlite();
truck_trypes_combo.ItemsSource = truckypessqlite.GetAllTruckTypes();
In my TruckTypesqlite
class TruckTypesSqlite {
public List<TruckTypesModel> GetAllTruckTypes()
{
//fetch data from sqlite and return a list of type TruckTypesModel
}
}
The TruckTypesModel
class consists of an id and description properties.
The above works but am now how do i set the selected item of the combobox suppose that i have an id of 25
After a few research i found out that i need to set the SelectedIndex
being new to c# how do i get the index of a value like 25 in the list returned by GetAllTruckTypes() so that i can simply do
public void setSeletedValue(){
//set the index of id value 25
truck_trypes_combo.SelectedIndex = ;//index of id value 25
}
Try this:
public void setSeletedValue(int id)
{
var allTruckTypes = truckypessqlite.GetAllTruckTypes();
int index = allTruckTypes.FindIndex(t => t.id == id);
if (index != -1)
{
truck_trypes_combo.SelectedIndex = index;
}
}
You may also need to improve the code by making allTruckTypes
a public property so it can be reused in multiple methods, also use data binding for the SelectedItem
of the combo box instead of setting its SelectedIndex explicitly.
But since you have just started to use C#, I am just showing you how to find the item (and its index) from the list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.