简体   繁体   English

仅在GridView中显示某些列表对象属性

[英]Only Display Certain List Object Properties in GridView

I've got a GridView control which is bound to a List of custom objects. 我有一个GridView控件绑定到自定义对象List 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. 这些对象有5个属性,但是,我不想在GridView中为所有属性生成一个列,仅针对某些属性。 I know how to turn off 'AutoGenerateColumns', however, I'm not sure how to then only display certain properties of each object selectively. 我知道如何关闭'AutoGenerateColumns',但是,我不知道如何只选择性地显示每个对象的某些属性。 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> 假设我有一个这样的列表: List<Car> cars = new List<Car>

Each Car has a property for Model , Make , Year , Transmission , Color . Car都有ModelMakeYearTransmissionColor的属性。

I want my GridView control to be bound to the cars List , but only have columns showing Model , Make , and Year . 我希望我的GridView控件绑定到汽车List ,但只有列显示ModelMakeYear

You need to create a BoundField or a TemplateField. 您需要创建BoundField或TemplateField。 Eg 例如

<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>

You would need to create a BindingList<yourObject> . 您需要创建一个BindingList<yourObject> Essentially it's like a List but makes it easier to bind to as a data source. 本质上它就像一个List,但更容易绑定到数据源。

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. 然后在前端的列集合中,您将使用DataPropertyName属性显示要显示的每个属性的Public属性。 Check out the following article. 看看下面的文章。 Hope this helps. 希望这可以帮助。

Binding a GridView to a collection 将GridView绑定到集合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM