使动态创建的单选按钮执行常见事件

时间:2014-01-22 20:45:32

标签: c# events dynamic radio-button

我的表单中有一个名为Button1的按钮,以及一个名为TexBox1的文本框。

我已经编写了代码,当我点击按钮时,会创建一个单选按钮来创建自己的名字:

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;

namespace WebApplication7
{
    public partial class WebForm1 : 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)
        {

            HtmlGenericControl div = new HtmlGenericControl("div");
            for (int i = 0; i < Convert.ToInt32(ViewState["Counter"]); i++)
            {
                RadioButton rb = new RadioButton();
                rb.GroupName = "GN1";
                rb.ID = i.ToString();
                rb.Text = "Button" + i.ToString(); 
                div.Controls.Add(rb);
                Panel1.Controls.Add(div);

            }
            ViewState["Counter"] = Convert.ToInt32(ViewState["Counter"]) + 1;


        }
    }
}

我的问题是,当我点击单选按钮时,我希望TextBox1.Text获取单击的单选按钮的文本:

TextBox1.Text=rb.Text;

如何将其应用于任何单选按钮?

3 个答案:

答案 0 :(得分:0)

在生成CheckedChanged控件时尝试订阅RadioButton事件:

for (int i = 0; i < Convert.ToInt32(ViewState["Counter"]); i++)
{
    RadioButton rb = new RadioButton();
    rb.CheckedChanged += (s, a) => TextBox1.Text = ((RadioButton)s).Text;
    ...
    ...
}

答案 1 :(得分:0)

您可以使用此方法:

private void radioButton_CheckedChanged(object sender, EventArgs e)
{
    RadioButton btn = sender as RadioButton;
    textBox1.Text = btn.Text;
}

创建RadioBUtton时需要将其附加到Checked Changed事件

rb.CheckedChanged += radioButton_CheckedChanged;

答案 2 :(得分:0)

RadioButton rb = new RadioButton();
rb.OnMouseDown+= SomeMethod_Click;

在您拥有自己的方法之后:

private void SomeMethod_Click(object sender, RoutedEventArgs e)
{
    // Here your logic
}