JToland
JToland

Reputation: 3710

Only Display Certain List Object Properties in GridView

I've got a GridView control which is bound to a List of custom objects. The objects have 5 properties, however, I don't want to generate a column in the GridView for all the properties, only for certain ones. I know how to turn off 'AutoGenerateColumns', however, I'm not sure how to then only display certain properties of each object selectively. Does anyone know how this should be done or can provide me with an example of doing this?


EXAMPLE:

Let's say I have a list like so: List<Car> cars = new List<Car>

Each Car has a property for Model, Make, Year, Transmission, Color.

I want my GridView control to be bound to the cars List, but only have columns showing Model, Make, and Year.

Upvotes: 3

Views: 2755

Answers (2)

gsirianni
gsirianni

Reputation: 1364

You would need to create a BindingList<yourObject>. Essentially it's like a List but makes it easier to bind to as a data source.

Then in your column collection on the front end you would then use the DataPropertyName property to display the Public property for each property you want to display. Check out the following article. Hope this helps.

Binding a GridView to a collection

Upvotes: 0

Dave Walker
Dave Walker

Reputation: 3523

You need to create a BoundField or a TemplateField. E.g.

<asp :GridView ID=“GridView1″ runat=“server”>
    <columns>
        <asp :BoundField DataField=“ColumnName”
            DataFormatString=“{0:M-dd-yyyy}”
            HtmlEncode=“false”
            HeaderText=“ColumnName” />
        </columns>
</asp:GridView>

or

<asp:TemplateField>
        <HeaderTemplate>Make</HeaderTemplate>
        <ItemTemplate><%# DataBinder.Eval(Container.DataItem, 
                     "Make")%></ItemTemplate>
</asp:TemplateField>

Upvotes: 2

Related Questions