2

我有一个带有单选按钮列表和文本区域的页面。数据根据用户的选择在文本区域内动态显示。我还设置了一个 OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged" 来创建一个允许用户引用他们的文章的 URL(单选按钮选择)。

除了将创建的 url(即http://test.com/test.aspx?selected=3)剪切并粘贴到新浏览器中之外,一切正常。代码不断将radiobuttonlist1.selectedindex 分配给-1。

所以这就是我在调试模式下看到的

案例 1当我将 url 剪切并传递到新浏览器http://test.com/test.aspx?selected=1时,在 page_load 方法代码的末尾 RadioButtonList1.SelectedIndex 等于 = -1。由于某种原因,它没有正确分配 selectindex。

案例 2当我在我启动的网页中选择一个单选按钮时,它会跳过 page_load 代码,因为post back 是 true。然后在 RadioButtonList1_SelectedIndexChanged 中创建一个 url。然后运行页面加载方法并在最后保持正确的 RadioButtonList1.SelectedIndex 值。

案例 3 当我在使用指向http://test.com/test.aspx?selected=2的启动网页中选择一个链接时,回发为假,因此它循环通过 page_load 代码并成功保存正确的 RadioButtonList1.SelectedIndex最后的价值。

protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
               {

                int selected;

                if (Request.QueryString["selected"] != null)
                {

                    if (int.TryParse(Request.QueryString["selected"], out selected))
                    {   


                       RadioButtonList1.SelectedIndex = selected;
                       RadioButtonList1.DataBind(); 

                    }


                }
                else
                {

                    int firstart = 0;      

                    RadioButtonList1.SelectedIndex = firstart;


                }

            }



        } 



    protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {



    }
    protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
        try{
        e.Command.Parameters["@URL_FK"].Value =  Session["URL_PK"];


        }
     catch (Exception ex)
     {

     }


    }


    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {


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

    }


}
4

2 回答 2

9

您需要反转调用以首先对单选按钮列表进行数据绑定,然后设置选定的索引。

例如,您可以重组为以下内容。如果你需要数据绑定,你可以把它放在我有评论的地方。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //Always bind the list to here, if needed

        if (Request.QueryString["selected"] != null)
        {
            int selected;
            if (int.TryParse(Request.QueryString["selected"], out selected))
            {   
                RadioButtonList1.SelectedIndex = selected;

            }
        }
    }
}

注意:我强烈建议进一步清理它,如果用户传递的“selectedindex”大于数据,则上述代码将出现异常。

于 2011-01-25T18:55:08.150 回答
0

我的会话参数在 SqlDataSource1_Selecting 上没有采用正确的值。我删除了在 aspx 中硬编码会话参数的代码,以使我的代码正常工作。感谢大家的投入!我很高兴这个结束了。

于 2011-02-01T17:18:02.800 回答