RadioButtons CheckedChanged事件

时间:2011-06-30 10:34:49

标签: c# asp.net controls

我在页面上有20个radiobuttons,我想知道它们中的哪一个被点击了。

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);
    }
}

我如何找到答案?

5 个答案:

答案 0 :(得分:2)

使用参数sender,您可以直接引用事件源控件。

var rb = (RadioButton)sender;

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

答案 1 :(得分:2)

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

您可以尝试上述方法。

更新:
要获取PlaceHolder中的所有选择单选按钮,请确保未在单选按钮上设置AutoPostBack。你不需要添加CheckChanged事件。 “r.CheckedChanged + = RadioButton1_CheckedChanged;” &lt; =删除。

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());

答案 2 :(得分:1)

 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;  



        }
    }

答案 3 :(得分:0)

你可以试试这个。

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

答案 4 :(得分:0)

将发件人转换为RadioButton:

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