【问题标题】:asp.net WebControl event order and ViewStateasp.net WebControl 事件顺序和 ViewState
【发布时间】:2011-10-19 13:37:11
【问题描述】:

我有一个创建下拉列表控件的自定义类,如下所示:

public class IHGridView : System.Web.UI.WebControls.WebControl
{
    private string _dataSource = "not set yet";

    public string DataSource
    {
        get { return _dataSource; }
        set { _dataSource = value; }
    }
}

编辑:

    protected override void OnInit(EventArgs e)
    {
        // VIewState is alive. When I select an option and submit, after postback it's selected value is the one I selected.
        this.Controls.Add(_dropDownList);
    }

    protected override void CreateChildControls()
    {
        // VIewState is dead. When I select an option and submit, after postback it's selected value is the default one.
        this.Controls.Add(_dropDownList);
    }

所以,现在我想出我必须在“OnInit”void 中添加控件的结果。 但是,这个“OnInit”是这个类写入的第一个 void。 如果我以前想使用像“DataSource”这样的属性,“OnInit”无效...... 我该怎么做?

编辑:

    protected void Button1_Click(object sender, EventArgs e)
    {
        IHGridViewTest2.DataSource = "fired";
    }

在触发 aspx 页面中的按钮时设置数据源。

【问题讨论】:

  • 触发按钮时。我编辑了问题。

标签: c# asp.net


【解决方案1】:

为什么要添加 _dropDownList 两次?一次在 OnInit 中就足够了,如果您希望在控件集合中添加 OnInit,则应将其添加到该位置 - 从而保持和恢复视图状态。

例如,要访问和绑定 _dropDownList,请覆盖 DataBind 方法 - 此时您可以使用所有属性。

protected override void DataBind(){
    base.DataBind();
    _dropDownList.DataSource = this.DataSource;
    _dropDownList.DataBind();
}

这是伪代码,未经测试或验证

编辑:

调用重写的 DataBind 方法

protected void Button1_Click(object sender, EventArgs e)
{
    IHGridViewTest2.DataSource = "fired";
    IHGridViewTest2.DataBind();
}

【讨论】:

  • 我的源代码中有“OR”。也许你没有仔细阅读我的问题。不管怎样,谢谢你的回答。
  • 问题已编辑,但我的回答仍然适用,保持在 OnInit 上添加的控件,然后如上所述覆盖 DataBind 方法,只需将按钮处理程序上的代码修改为:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-07
  • 1970-01-01
  • 2010-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-31
相关资源
最近更新 更多