Hello im makeing an application for school where we need to work with databases. Now i have one last error that i cant get to fix. I have a combobox where you can select a soccer league. Then the clubs of that league appear in a listbox. Based on what club you select the players from that club appear in an different listbox.
Now i have a method that takes the average cards given to the defenders of that club. If i first select a league, club, player and then change the league and select a club from the different league my application crashes. it gives me this error
System.InvalidCastException: Object cannot be cast from DBNull to other types
here is my code for the method im talking about.
public string GetGemKaart(string selecteditem)
{ //label gem kaarten per verdediger (club stat.)
using (MySqlConnection mysqlcon = new MySqlConnection(ConnectionString))
{
MySqlCommand mysqlCmd = mysqlcon.CreateCommand();
mysqlCmd.CommandText = "SELECT (AVG(GeleKaarten) + AVG(RodeKaarten)) FROM Spelers, clubs where clubs.naamClub = '" + selecteditem + "' and spelers.idclubs = clubs.idClubs and spelers.positie = 'V'";
mysqlcon.Open();
int returnvalue = (int)Convert.ToInt32(mysqlCmd.ExecuteScalar());
return returnvalue.ToString();
}
}
and the code where i call this method:
private void ListboxClubs_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ // Update de kampioenschappen en opgericht label wanneer een club is geselecteerd en laad spelers
if (listboxClubs != null && listboxClubs.SelectedItem != null)
{
string SelectedItem = listboxClubs.SelectedItem.ToString();
//laad spelers
List<Spelers> allspelers = db.Getspelers(SelectedItem);
listboxspelers.ItemsSource = allspelers;
//clubstatistieken
lblkampioen.Content = "Aantal kampioenschappen: " + db.Getkampioen(SelectedItem);
lblopgericht.Content = "Opgericht: " + db.Getopgericht(SelectedItem);
lblgemdoel.Content = "Gem. Doelpunten Per Aanvaller: " + db.GetGemDoel(SelectedItem);
lblgemkaart.Content = "Gem Kaarten Per Verdediger:" + db.GetGemKaart(SelectedItem);
}
}