TAGS :Viewed: 10 - Published at: a few seconds ago

[ Basic DataGridView questions ]

I have a datagridvew with a bindinglist whose datasource is to an intersection table. I have an another bindinglist which acts as a lookup and is bound to one of the columns that is a DataGridViewComboBoxColumn type. I have simplified the binding lists as shown below:

public IList<Flight> flights = new List<Flight>()
{
    new Flight { DepartureID = 1, DestinationID = 1, FlightNumber = "101" },
    new Flight { DepartureID = 2, DestinationID = 2, FlightNumber = "202" },
    new Flight { DepartureID = 3}
};

public IList<Departure> departures = new List<Departure>()
{   
    new Departure {ID = 1, City = "Toronto"},
    new Departure {ID = 2, City = "Chicago"},
    new Departure {ID = 3, City = "New York"}
};

public IList<Destination> destinations = new List<Destination>()
{
    new Destination {ID = 1, City = "London"},
    new Destination {ID = 2, City = "Paris"},
    new Destination {ID = 3, City = "Amsterdam"}
};

I have five columns in my datagridview:

  • Depature ID: Textbox
  • Departure: Textbox
  • Destination ID: Textbox
  • Destination: Combobox
  • Flight Number: Textbox

I have three questions:

1) The departures are readonly. I would like to display the ID and the city. How can I add textbox to automatically look up the City value. I thought of the OnCellPainting event and looking it up but the e.Value is readonly. Is there some OnCellDrawing event similar to Delphi.

2) On the combobox for Destinations, once an user selects a value from the combobox, how do I also update the Destination ID also?

3) How do I handle the scenario where I only have values for Departure (e.g. this record (new Flight { DepartureID = 3}) throws an invalid value error because there's no value for the combobox to lookup)

Answer 1


1) The easiest way to set your Departure city would be using a ComboBox like the destination. Binding it to the list of Destinations and marking this column as ReadOnly. This would handle the Departure with no code.

2) You should bind your DataGridView and your List of flights with a BindingSource. Because your ComboBox ValueMember is your ID and your DisplayMember is the name of the city, it will automatically update your ID.

3) If you want to bind your data, the template should be the same. You should always have a destination and flight number in your list. If they don't have value, set them to null. You're gonna be able to handle the null value while you can't handle a non-existent attribute.
new Flight { DepartureID = 3, DestinationID = null, FlightNumber = null }