RadioButtons CheckedChanged event

本文关键字:event CheckedChanged RadioButtons | 更新日期: 2023-09-27 18:00:40

我在页面上有20个单选按钮,我想知道其中哪一个被点击了。

protected void Page_Load(object sender, EventArgs e)
{
    Button newBTN = new Button();
    newBTN.Text = "Button 1";
    PlaceHolder1.Controls.Add(newBTN);
    for (int i = 0; i < 20; i++)
    {
       RadioButton r = new RadioButton();
       r.ID = i.ToString();
       r.CheckedChanged += RadioButton1_CheckedChanged;
       PlaceHolder1.Controls.Add(r);
    }
}

新更新的代码。。注意:该代码与上述代码无关。

      public List<int> ThreadID2Treat { get { return ViewState["Checked"] == null ? null : (List<int>)ViewState["Checked"]; } set { ViewState["Checked"] = value; } }
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)

var rad = (CheckBox)sender;
int threadID = int.Parse(rad.ID.ToString());
ThreadID2Treat.Add(threadID); 

}

public void DeleteButton_Clicked(object sender, EventArgs e)
{
    foreach (var item in ThreadID2Treat)
    {
        UsefulStaticMethods.DeleteThreads(item);
    }
}

我该如何发现?

RadioButtons CheckedChanged event

var rad = (RadioButton)sendder;
Response.Write("RadioButton Id :" + rad.Id.ToString());

你可以试试上面的。

更新:
要获取PlaceHolder中的所有选定单选按钮,请确保单选按钮上未设置"自动返回"。您不需要添加CheckChanged事件。"r.CheckedChanged+=单选按钮1_CheckedChanged;"<=去除

StringBuilder stringBuilder = new StringBuilder();
    foreach (var control in placeHolder1.Controls)
    {
        var rad = control as RadioButton;
        if (rad != null)
        {
            if (rad.Checked)
                stringBuilder.AppendLine(String.Format("Radion Button Checked : {0}", rad.ID));
        }
    }
    Response.Write(stringBuilder.ToString());

使用参数sender可以直接引用事件源代码管理。

var rb = (RadioButton)sender;

如果要直接触发此事件和回发,则必须将RadioButton的AutoPostBack-属性设置为true

 protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
    {
        if (sender is RadioButton)
        {
            RadioButton radioButton = (RadioButton)sender;
            //Code to use radioButton's properties to do something useful.
            // get the radio button by its ID
            string id = radioButton.ID;  

        }
    }

你可以试试这个。

RadioButton r = sender as RadioButton;
Response.Write(r.Id);

将发件人转换为RadioButton:

RadioButton r = sender as RadioButton;
if(r != null)
{
    //Do stuff
}