繁体   English   中英

方法不会正确地为selectindex赋值,asp.net radiobuttonlist

[英]method won't assign value to selectindex correctly, asp.net radiobuttonlist

我有一个带有radiobuttonlist和textarea的页面。 数据根据用户的选择在textarea中动态显示。 我还设置了一个OnSelectedIndexChanged =“RadioButtonList1_SelectedIndexChanged”来创建一个允许用户引用他们的文章的URL(单选按钮选择)。

一切都有效,除了将创建的URL(即http://test.com/test.aspx?selected=3 )剪切并粘贴到新的浏览器中。 代码保持将radiobuttonlist1.selectedindex分配给-1。

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

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

情况2当我在我启动的网页中选择一个单选按钮时,它会跳过page_load代码,因为回发是真的 然后在RadioButtonList1_SelectedIndexChanged中创建一个url。 然后运行on page load方法并在结尾处保存正确的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);

    }


}

您需要将对第一个数据绑定设备的调用反转为radiobuttonlist,然后设置所选索引。

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

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”大于数据,您将获得上述代码的异常。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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