2

我使用 ascx 用户控件来管理 CRUD o 数据库实体。我在我的 aspx 页面中重用了这个 userc 控件,以只读模式显示数据库上记录的数据库数据。用户控件内部有一个简单的 FormView 和一个 objectdatasource。

现在,在一个包含 ascx 的 aspx 页面中,我必须知道,在 aspx 的 DATABIND 时间中,数据库记录的一些数据是由用户控件考虑的。用户控件是在 aspx 页面之后的数据绑定,因此我没有数据。我必须在数据库的 aspx 页面中进行选择,并且在用户控件执行相同的选择之后。

我该如何优化这个过程?

4

2 回答 2

1

ASCX 基础事件可能会在您的 ASPX 基础事件之后触发,但在整个生命周期中,您可以触发自己的事件。

你可以在你的 ASCX 上定义一个事件,让你的页面注册到这个事件,然后将你的自定义事件从你的 ASCX 传播到你的 ASPX,参数中包含你需要的任何数据

粗略的例子(可能无法编译):在 ASCX

public partial YourControl : System.Web.UI.UserControl {
    public event EventHandler MyControlDataBound;
    public void FireMyControlDataBound()
    {
        if (MyControlDataBound!= null)
        {
            MyControlDataBound(this, new EventArgs());
        }
    }

    protected void MyDataBound(object sender, EventArgs e) {
        // ......
        FireMyControlDataBound();
    }
}

在 ASPX 中

public partial class MyPage: Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        yourUserControlInstance.MyControlDataBound += HandleYourDataInYourPage;
    }

    protected void HandleYourDataInYourPage(object sender, EventArgs e) {
        // .. do whatever needed in your page, with your data
        // if you have defined a custom Args class that inherits EventArgs, your could collect data here...
    }
}

如果您需要,请随意创建一个继承 EventArgs 的类以将数据与您的事件一起传递

于 2012-10-10T09:16:21.160 回答
0

您可以在 Page 的 init 事件中将参数传递给 UserContol

protected override void OnInit(EventArgs e)
{
        base.OnInit(e);
        var control = (UserControl)this.FindControl("UserControlId");
        control.Property = ...;//Pass User Control properties

}
于 2012-10-10T09:04:56.953 回答