简体   繁体   English

如何使用属性将类添加到GridView

[英]How to add a class to a GridView using attributes

i want to add items to a gridview in asp.net from a custom class. 我想从自定义类向ASP.NET中的gridview添加项目。 The class has Properties X and Y. Does anyone know if im able to add special attributes to these properties so i can just add the class and not have to muck around? 该类具有属性X和Y。是否有人知道我是否可以向这些属性添加特殊属性,以便我可以添加类而不用乱搞?

eg.. 例如..

[Column("Name")]
public string Name { get; set; }

Ideally i can then write something like.. 理想情况下,我可以写类似的东西..

this.gridview.datasource = instanceOfMyClass;

Suppose you have a DataObject class (equals to MyClass in your question) 假设您有一个DataObject类(等于您的问题中的MyClass

public class DataObject
{
   public int ID { get; set; }
   public string Name { get; set; }
}

The DataSource of the gridview is not an instance of DataObject but a List<DataObject> (or something equivalent), each DataObject refers to one row in the grid view. gridview的DataSource不是DataObject的实例,而是List<DataObject> (或类似的东西),每个DataObject引用网格视图中的一行。 On the other hand, it's not a good idea to use attributes marked in DataObject class. 另一方面,使用DataObject类中标记的属性不是一个好主意。 Specifying the DataField in the columns of the grid view is the easiest way. 在网格视图的列中指定DataField是最简单的方法。 Here is an example: 这是一个例子:

<asp:GridView ID="myGridView" runat="server">
    <Columns>
        <asp:BoundField DataField="ID" HeaderText="ID" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
    </Columns>
</asp:GridView>

And in code behind: 并在后面的代码中:

List<DataObject> data = GetTheData();
myGridView.DataSource = data;

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

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