为什么formview会在编辑模式中消失

时间:2013-11-19 00:14:09

标签: asp.net formview

我知道我必须遗漏一些简单的东西,但我找不到,所以我会在这里提出问题。我有一个带有两个模板的formview(item和edititem)。

表单绑定到page_Load事件中的itemtemplate并且工作正常。但是,如果在代码隐藏中使用!IsPostBack,则单击编辑按钮时,formview将消失。如果我从page_load删除回发检查,则在单击编辑按钮后会显示表单视图。

页面确实启用了视图状态。

通常,需要哪些步骤才能使formview在模式之间正确转换?

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        source = Session["Source"].ToString();
        acctType = Session["AccountType"].ToString();
        acctNumber = Convert.ToInt32(Session["AccountNumber"]);

        if (source == "LifeLineDS")
        {
            ObjectDataSource fvObjDS = new ObjectDataSource();
            fvObjDS.TypeName = "LifelineDataAccess.LifelineSubscriber";
            fvObjDS.SelectMethod = "GetLifelineDSSubscriber";

            fvObjDS.SelectParameters.Add(new Parameter("AcctType", TypeCode.String, acctType));
            fvObjDS.SelectParameters.Add(new Parameter("AcctNumber", TypeCode.String, Session["AccountNumber"].ToString()));
            fvObjDS.DataBind();

            if (fvObjDS != null)
            {
                fvSubscriber.DataSource = fvObjDS;  //subscriber.ToString();
                fvSubscriber.DataBind();

                initialProgramValue = (fvSubscriber.FindControl("txtEligibility") as TextBox).Text;
            }                
        }
// more code for other sources...
}

protected void btnEdit_Click(object sender, EventArgs e)
{
    fvSubscriber.ChangeMode(FormViewMode.Edit);
    fvSubscriber.DataSource = Session["subscriber"];  //Adding this line resolved !IsPostBack problem
    fvSubscriber.DataBind();

    ObjectDataSource programsObjDS = new ObjectDataSource();
    programsObjDS.TypeName = "LifelineDataAccess.LifelineSubscriber";
    programsObjDS.SelectMethod = "GetPrograms";

    DropDownList ddlEligibility = ((DropDownList)(fvSubscriber.FindControl("ddlEligibility")));

    if (ddlEligibility != null)
    {
        ddlEligibility.DataSource = programsObjDS;
        ddlEligibility.DataTextField = "ProgramName";
        ddlEligibility.DataValueField = "ProgramName";

        ddlEligibility.SelectedValue = initialProgramValue; // Set selected value to subscribers current program
        ddlEligibility.DataBind();
    }
} 

1 个答案:

答案 0 :(得分:0)

fvSubscriber.ChangeMode(FormViewMode.Edit);
fvSubscriber.DataBind();

似乎没有设置数据源。规则是您在代码的声明部分(DataSourceID*.aspx)中设置*.ascx,并且每次回发时自动完成绑定,或者以编程方式绑定,包括设置数据源并调用DataBind()

我的建议是将您的ObjectDataSource移至代码的声明部分,并将DataSourceID上的FormView设置为ID的{​​{1}} }。这很干净,很容易,而且装订工作总是如此。