开发者

ASP.NET Custom ObjectDataSource

I am trying to write a custom DataSource control by inheriting System.Web.UI.WebControls.ObjectDataSource. Here is my code for my data source class.

public class MyDataSource : ObjectDataSource
{
    public MyDataSource()
    {
        this.TypeName = GetType().FullName;
        this.SelectMethod = "S开发者_运维技巧electAll";
        this.SelectCountMethod = "SelectCount";
    }

    protected override void OnInit(System.EventArgs e)
    {
        base.OnInit(e);
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
    }

    [DataObjectMethod(DataObjectMethodType.Select)]
    public DataTable SelectAll()
    {
        // Do something using this.DataObjectTypeName
        DataTable dt = new DataTable();
        // Fill DataTable
        return dt;
    }

    public int SelectCount()
    {
        // Here is not important yet
        return 20;
    }
}

I use my data source as follows:

    <asp:GridView ID="grd" runat="server" AutoGenerateColumns="true" Width="100%"
    AllowPaging="true" AllowSorting="true" PageSize="10" DataSourceID="myDataSource">
    </asp:GridView>
    <cc2:MyDataSource ID="myDataSource" runat="server"
    DataObjectTypeName="MyLib.MyClass, MyLib">
    </cc2:MyDataSource>

No code is written in my aspx.cs file and my code works fine if I write a hardcoded select logic in SelectAll method. But when I tried to use DataObjectTypeName property in SelectAll method I saw that this property has an empty string value. I put four break points in my data source code. First in the constructer, second in OnInit, third in OnLoad and last in SelectAll methods. Here is the list of where code has stopped and values of DataObjectTypeName when I run the project.

1) @Constructer: DataObjectTypeName = ""
2) @OnInit     : DataObjectTypeName = "MyLib.MyClass, MyLib"
3) @OnLoad     : DataObjectTypeName = "MyLib.MyClass, MyLib"
4) @Constructer: DataObjectTypeName = ""
5) @SelectAll  : DataObjectTypeName = ""

Q1: Why constructer is invoked twice?

Q2: Why DataObjectTypeName property is not assigned after second invocation of constructer?

Thanks in advance,

Mehmet.


Instead of Inheriting from the ObjectDataSource just use it as it was intended and pack all your login into a seperate object (another class) that the ObjectDataSource will actually use. Read the MSDN documentation about the class, it is quite robust and allows for unlimited possibilities...

Q1) And for your question, the constructor is called twice because the ObjectDataSource is trying to instanciate itself (That's what it does when you supply a TypeName) Q2) Answer one explaings your second question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜