views:

43

answers:

2

So I have a collection that I have in a listbox right now, which displays each item in the collection. I want to turn the listbox into a gridview, so I can add checkboxes and other drop downs. I am unable to find a tutorial that explains how to do this.

For the example my collection has 2 items, each item has multiple columns.

  • [0] 747 Jet
    • [0] Passenger amount: 417
    • [1] First Flight: 1967
  • [0] A380
    • [0] Passenger amount: 853
    • [1] First Flight: 2005

Right now my listbox uses this code

foreach (AMAPnr.Airplane airElement in AMAPnr.Airplanes)
{
    lstPlanes.Items.Add(
        "PassengerAmount: " + airElement.Passenger + " First Flight:" +
         airElement.FirstFlight.ToString());
}

How would i go about changing this into a gridview?

+2  A: 

Update: The OP has clarified that they chose the wrong tags and this was actually for WinForms.

If you add a DataGridView to your form, and then put the following code in your forms codebehind, it works a treat:

private class Airplane
{
    public string AirplaneName { get; set; }
    public int PassengerAmt { get; set; }
    public int FirstFlight { get; set; }
}

public Form1()
{
    InitializeComponent();

    var planes = new List<Airplane>();
    planes.Add(new Airplane() { AirplaneName = "747 Jet", PassengerAmt = 417, FirstFlight = 1967 });

    dataGridView1.DataSource = planes;

}

I've used a custom Airplane class to show this example a I don't know precisely how your code's structured and it was easier for me that way. You should be able to plug in your custom datatype relatively easily.

Rob
I mistakenly added asp.net as one of my tags, will this work for window forms?
Spooks
@Spooks, Just tried it and it worked a treat, with no need for the `.DataBind()` line =)
Rob
@Rob thanks, I think its databinding, just not sure how to get it to display though. (headers/fill the columns)
Spooks
@Spooks - look at the example I've put in for WinForms, it displays all the columns/rows in your collection without having to configure anything. Obviously you'll have a much tidier UI if you do define the columns and any mappings though =)
Rob
If you want notifications for changes to elements consider using a BindingList<> rather than just List<>
robber.baron
Thank you so much, working perfectly. What is this technique called?
Spooks
Spooks, As I said earlier, data binding =) There's a summary page at http://msdn.microsoft.com/en-us/library/ms171600.aspx and a specific code sample from Microsoft at http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx =)
Rob
+1  A: 
    public IEnumerable<AMAPnr.Airplane> getItems(Planes)
    {
        foreach (AMAPnr.Airplane airElement in Planes)
        {
            yield return airElement;
        }
        yield break;
    }

Then just do myDataGrid.DataSource = getItems(AMAPnr.Airplanes);

You can also just do myDataGrid.DataSource = lstPlanes;

Brian