简体   繁体   中英

dynamically use radio buttons in asp.net applications

I am developping an asp.net application.

When a user clicks on a page, some radio buttons are added to the the page dynamically.

Then when he clicks on another "update" button, I would liek to check, which of the radio buttons are checked and post back them to the server.

The problem is the following:

I add dynamically the radio buttons in the page_load method.

But when I am on the update button onclick method, I cannot use them to check if they are checked ot not.

I have tried several methods like using a static dictionary of radiobuttons, but I cannot keep a reference on them, when I am on my update method.

This is my method when the page is loading:

private static Dictionary<string,RadioButton> buttons;

protected void Page_Load(object sender, EventArgs e)
{
    for (int i=0;i<5;i++)
    {
        RadioButton r = new RadioButton();
        r.Text = i.ToString();
        r.ID = i.ToString();;
        Panel1.Controls.Add(r);
        buttons.Add(i.ToString(), r);
    }
}

And this is my method when the user click on the update button where I would like to access to each of my radiobutton depending their id or their text, but I cannot : For example, If I want all the buttons from 1 to 3 to be checked :

protected void Button1_Click(object sender, EventArgs e)
{
    for (int i=1;i<4;i++)
    {
        buttons[i].checked=true;
    }
}

Asp.net will clear your dynamically added controls on every postback. if you want to get their selection you have to do that on client click of button in JS. C# Code:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            for (int i = 0; i < 5; i++)
            {
                RadioButton r = new RadioButton();
                r.Text = i.ToString();
                r.ID = i.ToString();
                r.ClientIDMode = System.Web.UI.ClientIDMode.Static;
                Panel1.Controls.Add(r);

            }
        }
    }

and JS Code:

<script type="text/javascript">
    function getCheckedRadios() {
        alert(document.getElementById('1').checked);
    }
</script>

aspx code for your button will be:

<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="getCheckedRadios(); return false;"/>

I hope it will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM