lundi 1 juin 2015

View state issues on adding a web forms use control at 0 index in OnLoad Event

With the attached demo code (see below), if I click the save button, there will occur a NullReferenceException. It looks like the AddAt is causing issue with the ViewState. Dynamic control should be added in the OnInit but I have a restriction that do not allow me to use that event. In fact, if I call the AddAt method in OnInit it will works fine, but that cannot work for me as explained above. I was wondering if exists an alternative way to add the user control at index 0 without use the OnInit Page event having the button beign able to read the selected value in the Click handler.

View

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

<!DOCTYPE html>

<html xmlns="http://ift.tt/lH0Osb">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList runat="server" ID="cb1"></asp:DropDownList>
        <asp:Button runat="server" ID="btnTest" Text="Save"/>
    </div>
    </form>
</body>
</html>

Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class Test : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        btnTest.Click += btnTest_Click;
    }

    private void btnTest_Click(object sender, EventArgs e)
    {
        btnTest.Text = cb1.SelectedItem.Value;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            cb1.DataSource = new string[] {"AAA", "BBB", "CCC"};
            cb1.DataBind();
        }

        var literal = new Literal { Text = "Dynamic Control" };
        Controls.AddAt(0, literal);
    }
}

Any idea?




Aucun commentaire:

Enregistrer un commentaire