Search code examples
c#asp.netradiobuttonlist

Modify page_load method for radiobuttonlist


I have a page with radio buttons and a textarea that populates data dynamically based on your selection. The radio buttons act as a list of article titles and on selection you see the content of the article.

Within my pageload method, I want to allow users to be able to see a URL in their browser that points to value they've. That way they can link to the article within another source.

Currently, the method I have allows me to link to the button selection if I manually type in the following example URLs:

http://localhost/test/Articles_test.aspx?selected=1
http://localhost/test/Articles_test.aspx?selected=2

I'd like to modify this so that the URL appears in the browser when a radio button selection is made. Plus, on page load defaults to the "0" index if no value parameter was specified.

protected void Page_Load(object sender, EventArgs e)
{    
    if (!IsPostBack)
    {
        int selected;

        if (int.TryParse(Request.QueryString["selected"], out selected))
            RadioButtonList1.SelectedIndex = selected;
            RadioButtonList1.DataBind();         
    }
}



protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{

        string strRedirect;
        strRedirect = "frm_Articles.aspx?selected=" + RadioButtonList1.SelectedIndex;
        Response.Redirect(strRedirect);

}

Solution

  • Set your radiobutton list to post back on change. Then, in the handler, do a redirect to the appropriate URL:

    protected void Page_Load(object sender, EventArgs e)
    {    
        int selected;
    
        if (int.TryParse(Request.QueryString["selected"], out selected))
            RadioButtonList1.SelectedIndex = selected;
            RadioButtonList1.DataBind();         
    }
    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {
    
        string strRedirect;
        strRedirect = "frm_Articles.aspx?selected=" + RadioButtonList1.SelectedIndex;
        Response.Redirect(strRedirect);
    }