Asp.net How can ObjectDataSource access System.Web.UI.Page objects

I am using an ObjectDataSource as shown below.

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

When starting InsertMethod mode, everything works 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;
    }

He does not know my label object, which is represented in my aspx file.

enter image description here

I read this one to find a suitable solution.

But I still do not understand how to do this.

Every suggestion will be appreciated.

+3
source share
2 answers

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

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

Put it in Page_Load or Page_Init

+1
source

...
<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">
.....
-1

All Articles