I have a combo box where which gets values from an API. I want to get the ID of the selected item in that combobox because the data in my next view changes based on the value selected here.
My Combobox.
<ComboBox x:Name="cmbSubjects" HorizontalAlignment="Right" Background="#FFE5DBE8" Width="141" SelectedItem="Maths" Margin="0,217,957,247" ItemsSource="{Binding Source={StaticResource cvsSubjects}}" PlaceholderText="Select"/>
This is how I populate it.
private async void getSubjects()
{
try
{
string subjects = baseAddress + "subjects";
var cont = await httpClient.GetStringAsync(new Uri(subjects));
subjectHelper data = JsonConvert.DeserializeObject<subjectHelper>(cont);
foreach (var item in data.result)
{
cmbSubjects.Items.Add(item.name);
}
}
catch (Exception ex)
{
MessageDialog messageDialog = new MessageDialog(ex.Message);
messageDialog.ShowAsync();
}
}
My Classes:
public class Subject
{
public int id { get; set; }
public string name { get; set; }
public string code { get; set; }
public string description { get; set; }
public curriculum curriculam { get; set; }
}
class subjectHelper
{
public List<Subject> result { get; set; }
}
public class unit
{
public int id { get; set; }
public string name { get; set; }
public string code { get; set; }
public string description { get; set; }
public string image { get; set; }
public int teachingHours { get; set; }
public int isMandotory { get; set; }
public Subject subject { get; set; }
}
class unitHelper
{
public List<unit> result { get; set; }
}
The user will be able to select the Subject in the combo box so I want it to return the Subject so I can load the units dynamically according to the subject.
Someone please help me do this.. Any kind of help is appreciated......
You need to change your code a little for this.
<ComboBox x:Name="cmbSubjects" HorizontalAlignment="Right" Background="#FFE5DBE8" Width="141" SelectedItem="Maths" Margin="0,217,957,247" PlaceholderText="Select"> <ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
and set itemssource as follows:
cmbSubjects.ItemsSource=data.Result;
and then in SelectionChanged event
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Subject selectedSubject = cmbSubjects.SelectedItem as Subject;
if(selectedSubject!=null){
int selectedSubID = selectedSubject.ID;}
}