Saturday, February 19, 2011

How do you select what properties will be displayed when databinding to a DataGridView?

Binding a List collection to a datagrid. How can you limit what properties will be displayed?

DataGridViewAirport.DataSource = GlobalDisplayAirports
From stackoverflow
  • Turn off AutoGenerateColumns, and then you can explicitly create the columns you need. For example here's an example:

    <asp:GridView ID="myGrid" runat="server" AutoGenerateColumns="False" CellSpacing="0">
        <Columns>
         <asp:BoundField DataField="Total" HeaderText="Amount" DataFormatString="{0:C}"/>
    
        </Columns>
    

    Another option would to be hide the columns after you data bind, but this above is a better approach.

    : Thanks Josh, sorry should have been more specific, I am using Windows Forms.
    JoshBerke : Ok solution is still the same, just my sample is off.
  • Depending on your dataSource you could mark the properties you don't want to show then you can leave autogenerate columns on.

    I believe this is correct VB:

    <System.ComponentModel.Browsable(false)> _
    

    in C# it is

    [System.ComponentModel.Browsable(false)]
    

    Another Useful attribute is

    [DisplayName("Total Amount")]
    

0 comments:

Post a Comment