asp.net回发重新渲染已经动态添加的控件

时间:2015-03-16 09:46:34

标签: c# asp.net

我在页面加载时动态添加单选按钮,我想要何时单击页面上的按钮以了解所选单选按钮。我尝试了很多,但似乎当页面被回发时,动态添加的控件已经消失。

我想问一下是否有办法重新渲染这些控制器。

所有控件都以ID开头

原因_

我希望你帮助我,如果你想知道我的代码,我已经在这里发布了另一个问题ASP.NET Find Control by its Partial ID(请不要将其标记为重复,因为那是关于部分ID,但现在我知道我必须重新渲染页面)

Update1

评论之后,我写了这段代码:

protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {
        //here i add the radio buttons automatically
        DataTable results = new DataTable();
        //i fill the results data table from database
        ViewState["numberOfReasons"] = results.Rows.Count;
        foreach (DataRow row in results.Rows)
        {
            RadioButton radioButton = new RadioButton();
            radioButton.ID = "reason_" + row["reasonName"].ToString();
            radioButton.GroupName = "reason";
            radioButton.Text = row["reasonName"].ToString();
            ViewState["reason_" + numberOfReasons] = row["reasonName"];
        }
    }
}

如你所见,我在视图状态中保存了多个原因,并在视图状态中保存了所有原因,

我在页面init

中这样做
protected void page_init(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        int numberOfReasons = int.Parse(ViewState["numberOfReasons"].ToString());
        for (int i = 0; i < numberOfReasons; i++)
        {
            RadioButton r = (RadioButton)Page.FindControl(ViewState["reason_" + i].ToString());
            if (r.Checked)
            {
                Console.Write("I will not swear on Stack Overflow.");
            }
        }
    }
}

但是我在这一行中得到了null异常

 int numberOfReasons = int.Parse(ViewState["numberOfReasons"].ToString());

如何解决这个例外,这是正确的解决方案吗?

更新2

在新的ansewr之后,我必须告诉你我在哪里添加我的单选按钮,我将每四个单选按钮添加到这样的div,然后我将 new div 添加到myValueDiv,因为这:

int numberOfReasons = 0; // a integer variable to know if the number of the reasons becomes able to be divided by four
            HtmlGenericControl div = null;
            foreach (DataRow row in results.Rows)
            {
                numberOfReasons++;

                if ((numberOfReasons % 4) == 1)
                {
                    div = new HtmlGenericControl("div");
                    div.Attributes.Add("class", "oneLine");
                }

                RadioButton radioButton = new RadioButton();
                radioButton.ID = "reason_" + row["reasonName"].ToString();
                radioButton.GroupName = "reason";
                radioButton.Text = row["reasonName"].ToString();

                div.Controls.Add(radioButton);
                if (numberOfReasons % 4 == 0)
                {
                    myValueDiv.Controls.Add(div);
                    //numberOfReasons = 0;
                }
                else if (numberOfReasons == results.Rows.Count)
                {
                    myValueDiv.Controls.Add(div);
                    //numberOfReasons = 0;
                }
            }

2 个答案:

答案 0 :(得分:1)

这是经过验证的代码。

Aspx代码

<form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="btn_Click" />
    </div>
</form>

CS代码

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CreateDynamicControls();
        }
    }

页面加载将在第一次加载控件。

    protected override object SaveViewState()
    {
        //save view state right after the dynamic controlss added
        var viewState = new object[1];
        viewState[0] = base.SaveViewState();
        return viewState;
    }

SaveViewState()会在动态控件添加到页面表单后立即保存视图状态。

    protected override void LoadViewState(object savedState)
    {
        //load data frm saved viewstate
        if (savedState is object[] && ((object[])savedState).Length == 1)
        {
            var viewState = (object[])savedState;
            CreateDynamicControls();
            base.LoadViewState(viewState[0]);
        }
        else
        {
            base.LoadViewState(savedState);
        }
    }

LoadViewState()将从维护的视图状态

加载数据
    protected void btn_Click(object sender, EventArgs e)
    {
        //Make sure only dynamic controls get selected for process
        foreach (Control cntrl in this.Form.Controls.OfType<RadioButton>().Where(x => x.ID.Contains("reason")))
        {
            bool option = ((RadioButton)cntrl).Checked;
        }
    }

btn_Click可以是您使用的任何回发事件,演示回发

创建动态控件的方法

    private void CreateDynamicControls()
    {
        List<string> optionList = new List<string> { "opt1", "opt2", "opt3" };
        foreach (string row in optionList)
        {
            RadioButton radioButton = new RadioButton();
            radioButton.ID = "reason_" + row;
            radioButton.GroupName = "reason";
            radioButton.Text = row;
            this.Form.Controls.Add(radioButton);
        }
    }

答案 1 :(得分:0)

我使用简单的功能只是为了使用您的场景检查基本概念。我做的如下:

<强> ASPX:

 <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

CS:

 protected void page_init(object sender, EventArgs e)
{
    List<string> TempList = new List<string>();
    TempList.Add("Name1");
    TempList.Add("Name2");
    TempList.Add("Name3");
    TempList.Add("Name4");
    TempList.Add("Name5");
    TempList.Add("Name6");
    ViewState["numberOfReasons"] = TempList.Count;
    int i = 1;
    foreach (string row in TempList)
    {
        RadioButton radioButton = new RadioButton();
        radioButton.ID = "reason_" + i.ToString();
        radioButton.GroupName = "reason";
        radioButton.Text = row;
        ViewState["reason_" + row] = row;
        this.Form.Controls.Add(radioButton);
        i++;
    }
}

 protected void Button1_Click(object sender, EventArgs e)
{
    foreach (Control cntrl in this.Form.Controls.OfType<RadioButton>().Where(x => x.ID.Contains("reason")))
    {
        bool option = ((RadioButton)cntrl).Checked;
        if (option)
        {
            Label1.Text = cntrl.ID + " Checked";
        }
    }
}

即使在回发后我也可以选中复选框。我不知道你哪弄错了。希望这会对你有所帮助。