Home > Back-end >  Change ComboBox displayed text at runtime WPF
Change ComboBox displayed text at runtime WPF

Time:11-19

So I have a program that pulls items from a Microsoft Access DB and puts them into a list. This list is then returned and the ComboBox ItemSource is bound to this returned list:

Main Window Code:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        clsFlightManager flightManager = new clsFlightManager();
        InitializeComponent();
        cbChooseFlight.ItemsSource = flightManager.getFlights();
    }
}

clsFlightManager:

internal class clsFlightManager
{
    clsDataAccess da = new clsDataAccess();

    public List<clsPassenger> ?lstPassenger;
    public List<clsFlight> ?lstFlight;

    public List<clsFlight> getFlights()
    {
        lstFlight = new List<clsFlight>();
        int iRet = 0;
        string sSQL = clsFlightSQL.getFlights();
        DataSet ds = da.ExecuteSQLStatement(sSQL, ref iRet);
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            clsFlight flight = new clsFlight();
            flight.FlightID = dr[0].ToString();
            flight.FlightNumber = dr[1].ToString();
            flight.AircraftType = dr[2].ToString();
            lstFlight.Add(flight);
        }
        return lstFlight;
    }
}

clsFlightSQL code:

internal class clsFlightSQL
{
    public static string getFlights() 
    {
        string sSQL = "SELECT Flight_ID, Flight_Number, Aircraft_Type FROM FLIGHT";
        return sSQL;
    }
}

clsFlight code:

internal class clsFlight
{
    public string FlightID { get; set; }
    public string FlightNumber { get; set; }
    public string AircraftType { get; set; }
}

The DataAccess class just runs the SQL statement

I have ran through the debugger and the list is populated with the correct information from the database. However, the text the ComboBox displays is ProjectName.clsFLight. How can I change the display text to show the information in the list (example being FlightNumber - AircraftType) instead of ProjectName.clsFlight

CodePudding user response:

Give your class a ToString() method

internal class clsFlight
{
    public string FlightID { get; set; }
    public string FlightNumber { get; set; }
    public string AircraftType { get; set; }

    public override string ToString()
    {
        return $"{FlightNumber} - {AircraftType}";
    }
}
  • Related