动态创建的单选按钮不会在单击时执行事件

时间:2014-01-31 20:27:02

标签: c# asp.net

我的表单中有一个名为“添加单选按钮”的按钮,以及一个名为TexBox1的文本框。

我编写了代码,当我点击“添加单选按钮”时,它会生成一个单选按钮;它的名字是:

C#:

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 Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState["Counter"] = 0;
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i <= Convert.ToInt32(ViewState["Counter"]); i++)
        {
            HtmlGenericControl div = new HtmlGenericControl("div");
            RadioButton rb = new RadioButton();
            rb.ID = i.ToString();
            rb.Text = "Button" + i.ToString();
            rb.GroupName = "RB";
            rb.CheckedChanged += radioButton_CheckedChanged;

            div.Controls.Add(rb);
            Panel1.Controls.Add(div);
        }

        ViewState["Counter"] = Convert.ToInt32(ViewState["Counter"]) + 1;
    }
    private void radioButton_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton btn = sender as RadioButton;
        TextBox1.Text = btn.Text;
    }

}

ASP

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:Panel ID="Panel1" runat="server">
        </asp:Panel>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add RadioButton" />

    </div>
    </form>
</body>
</html>

问题是,在创建几个单选按钮之后,我希望程序工作就好像每个单元都被选中一样,TextBox1.Text获取单选按钮的文本字符串(按钮的名称),但函数radioButton_CheckedChanged不会执行。

3 个答案:

答案 0 :(得分:2)

你错过了我认为

rb.CheckedChanged +=new EventHandler(rb_CheckedChanged);

检查下面的评论

答案 1 :(得分:0)

你应该将其设置为真实的Autopostback属性

 rb.AutoPostBack = true;

答案 2 :(得分:0)

this is how its should be imo:

protected void Button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i <= Convert.ToInt32(ViewState["Counter"]); i++)
        {
            HtmlGenericControl div = new HtmlGenericControl("div");
            RadioButton rb = new RadioButton();
            rb.ID = i.ToString();
            rb.Text = "Button" + i.ToString();
            rb.GroupName = "RB";
            rb.CheckedChanged += +=new EventHandler(radioButton_CheckedChanged);

            div.Controls.Add(rb);
            Panel1.Controls.Add(div);
        }

        ViewState["Counter"] = Convert.ToInt32(ViewState["Counter"]) + 1;
    }
    private void radioButton_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton btn = sender as RadioButton;
        TextBox1.Text = btn.Text;
    }