asp.net how can ObjectDataSource access System.Web.UI.Page objects

这一生的挚爱 提交于 2019-12-07 16:12:26

问题


I use ObjectDataSource as below.

<asp:ObjectDataSource ID="Item" runat="server" 
                SelectMethod="Grid_DataBind" TypeName="XXX.XXX.XXX" 
                DataObjectTypeName="Controller.Items" UpdateMethod="UpdateRow_Grid"
                InsertMethod="InsertRow_Grid">

When InsertMethod fire, everything work fine but ...

public IList<Items> InsertRow_Grid(Items item)
    {
        item.ID = System.Guid.NewGuid().ToString();          
        bool contains = GridSource.AsEnumerable()
                        .Any(row => item.JobID == row.JobID);
        if (!contains)
        {
            GridSource.Add(item);              
        }
        else
        {              
           lblMsg.Text= "This record has already exists.";               
        }
        return GridSource;
    }

It doesn't know my label object which is presented in my aspx file.

I had read this so that I can search proper solution.

But I still don't get how to do.

Every suggestion will be appreciated.


回答1:


This is because asp:ObjectDataSource creates new instance of object you specified in "TypeName" property To use current page object instead of creating new, you need this code:

YourObjectDataSource.ObjectCreating += (s, a) => { a.ObjectInstance = this; };

Place it in Page_Load or Page_Init




回答2:


You can add this code to your page

...
<asp:Label id="lblMsg" runat="server"/>
<asp:ObjectDataSource ID="Item" runat="server" 
            SelectMethod="Grid_DataBind" TypeName="XXX.XXX.XXX" 
            DataObjectTypeName="Controller.Items" UpdateMethod="UpdateRow_Grid"
            InsertMethod="InsertRow_Grid">
.....


来源:https://stackoverflow.com/questions/12797631/asp-net-how-can-objectdatasource-access-system-web-ui-page-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!