如何将 GridView 绑定到自定义对象? [英] How do I bind a GridView to a custom object?

查看:33
本文介绍了如何将 GridView 绑定到自定义对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下 ASP.NET 代码(它不完整 - 显然有很多缺失,但都不重要):

If I have the following ASP.NET code (it's not complete - obviously there's a lot missing, but none of it matters):

    <asp:GridView>
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    My Label: <asp:Label />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    My Text Box: <asp:TextBox />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

如果我在 CodeBehind 中有这样的东西:

And if I have something like this in the CodeBehind:

Private MyListOfObjects As List(Of MyObject)

...

Public Class MyObject

    Public MyTextBoxString as String
    Public MyLabelString as String

End Class

如何绑定 GridView 以便一行相当于我的 MyListOfObjects 列表中的一项,并且数据将在页面加载或回发时填充和保留?我以前从未做过这样的自定义数据绑定,所以完整的解释会非常有帮助.到目前为止,我遇到的所有教程都只讨论了将 GridViews 直接用于数据库查询结果,这不是我需要的.

How can I bind the GridView so that one row is equivalent to one item in my MyListOfObjects list, and so that the data will populate and persist across page loads or postbacks? I've never done custom databinding like this before, so a full explanation would be very helpful. All the tutorials I've come across so far only talk about using GridViews directly with Database query results, and that's not what I need.

谢谢!

推荐答案

只需将 gridview 的数据源设置为您的对象即可.

Just set the datasource of the gridview to your object.

MyGridView.DataSource = myList
MyGridView.DataBind()

这是一个非常相似的帖子:

Here's a very similiar post:

绑定返回列表的方法<员工>到网格视图

看起来您正在使用 vb.net 中的列表.记住列表可以包含整数、字符串、日期、对象(这些包括用户定义的类型(您的对象)).因此,您可以通过将数据源属性设置为列表来将 gridview 绑定到列表对象.

Looks like you are using a list in vb.net. Remember lists can hold integers, strings, dates, objects (these include user defined types (your object)). So you can bind a gridview to a list object by setting the datasource property to your list.

在上面的示例中,myList 可能包含大量员工对象等.因此,将其分配给数据源和 .DataBind() 并瞧瞧每行都包含您的对象的 gridview.

In the above example, myList, might hold a ton of employee objects, etc. So assign it to the datasource and .DataBind() and voila a gridview with each row containing your object.

这篇关于如何将 GridView 绑定到自定义对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆