【问题标题】:Get Business Object back from Grid View从网格视图中获取业务对象
【发布时间】:2011-03-06 16:44:19
【问题描述】:

e.Row.DataItem 究竟是什么返回.. MSDN 说.. 返回一个表示 GridViewRow 对象绑定到的底层数据对象的对象。

这是我的数据网格...

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1" OnRowDataBound="GridView1_RowDataBound">
        <Columns>
            <asp:BoundField DataField="PracticeCode" HeaderText="PracticeCode" SortExpression="PracticeCode" />
            <asp:BoundField DataField="AccountNo" HeaderText="AccountNo" SortExpression="AccountNo" />
            <asp:BoundField DataField="PatientName" HeaderText="PatientName" SortExpression="PatientName" />
            <asp:TemplateField HeaderText="Status">
                <ItemTemplate>
                    <asp:Label ID="LblStatus" runat="server"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

我将它与我的业务对象绑定 List .. 在行 DataBound 事件中,我尝试这个...

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        Patient p1 = (Patient)e.Row.DataItem;
        Label lbl = e.Row.FindControl("LblStatus") as Label;

        if (p1 == null)
        {
            throw new Exception("P1 is null");
        }

        if (p1.OpenItems.Count > 0)
        {
            lbl.Text = "Has open Items";
        }
        else
        {
            lbl.Text = "";
        }
    }

我得到异常P1 为空...为什么...我错过了什么...

注意:可能还有其他方法可以做到这一点,但我特别想知道为什么我的 p1 为空......并且有什么方法可以让 Patient 绑定后从 GridView 返回的对象。

【问题讨论】:

    标签: c# asp.net gridview business-objects


    【解决方案1】:

    页眉和页脚也会调用 RowDataBound,在调用 e.Row.DataItem 之前,您需要确保您当前处于实际的 DataRow 中:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {                
           if(e.Row.RowType != DataControlRowType.DataRow)
              return;
    
           Patient p1 = (Patient)e.Row.DataItem;
    

    【讨论】:

    • 是的,这个事件也被称为标题并不是很明显......这将是有意义的方式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多