【问题标题】:C# - Use same object for multiple columns in GridViewC# - 为 GridView 中的多个列使用相同的对象
【发布时间】:2011-05-05 05:12:26
【问题描述】:


我有一个填充有 Enrollment 对象的学生注册网格视图。 Enrollment 对象具有学生 ID。使用该 ID,我正在填充注册 gridview 的 2 列(来自 Student 对象的 3 个属性)。
现在,我正在使用以下代码进行操作。这意味着同一个对象需要 3 次往返数据库,这非常糟糕。如何使用同一个对象来获取 3 个属性?

<asp:TemplateField HeaderText="Student Name">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%# string.Format("{0} - {1}", StudentProfile.GetStudentProfileById(Convert.ToInt32(Eval("StudentId"))).FirstName, StudentProfile.GetStudentProfileById(Convert.ToInt32(Eval("StudentId"))).Surname) %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Student DOB">
                <ItemTemplate>
                    <asp:Label ID="lblDOB" runat="server" Text='<%# StudentProfile.GetStudentProfileById(Convert.ToInt32(Eval("StudentId"))).DateOfBirth %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

编辑:仅供参考,我必须处理更新 gridview 行,这将涉及向每一行添加文本框等。你能把答案保持在这一点上吗?

非常感谢!

【问题讨论】:

    标签: c# asp.net data-binding gridview


    【解决方案1】:

    您将数据绑定到 gridview 的方式是错误的。您需要在对象/集合中获取Data,然后将该数据作为DataSource 绑定到您的GridView

    看看这里Displaying Data With the ObjectDataSource,也看看这个Querying Data with the SqlDataSource Control

    【讨论】:

    • 你的意思是我应该创建一个类来存储由 GridView 列反映的中间对象?
    • 您可以一次从数据库中获取所有数据,然后将其放入某个集合/数据表中,然后将该集合/数据表绑定到您的 grdivew
    猜你喜欢
    • 2023-03-31
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    相关资源
    最近更新 更多