change the selected value of a dropdownlist inside nested repeater

▼魔方 西西 提交于 2020-01-02 08:28:23

问题


I tried to change a dropdownlist selected value from a c# code :

<repeater >
   <repeater> 
      <dropdown>

and I add a datasource in aspx page to the dropdown every thing works fine .. but I want to change the selected value onload of the dropdown to be able to show the user the previous selected name when edit the table

protected void PrepairDropDownList(object sender,EventArgs e)
    {
        shiftrepeater.DataBind();
        if (shiftrepeater.Items.Count > 0)
        {
            for (int shiftcount = 0; shiftcount < shiftrepeater.Items.Count; shiftcount++)
            {
                Repeater temp = (Repeater)shiftrepeater.Items[shiftcount].FindControl("saturdayrepeater");
                if (temp.Items.Count > 0)
                {
                    for (int count = 0; count < temp.Items.Count; count++)
                    {
                        DropDownList ds = (DropDownList)temp.Items[count].FindControl("userdropdown");
                        HiddenField hf = (HiddenField)temp.Items[count].FindControl("hiddenid");//contain the id if the field 
                        SarcShiftUser user = CRUD<SarcShiftUser>.Get(int.Parse(hf.Value)); //a method to select a user with a specific id and add it to object from class sarcshiftuser

                        if (user.id == 0)
                            ds.SelectedValue = "";
                        else
                        {
                            ds.SelectedValue = user.user_id + "";

                        }
                    }
                }

            }
        }
        shiftrepeater.DataBind();
    }

I add this method to Onload of the repeater : but nothing change and the previous name didn't show

P.S : the user object is correct and the user.user_id is also correct P.S 2 : I tried to add a ds.DataBind(); after changing the selected but give that error :

System.ArgumentOutOfRangeException: 'userdropdown' has a SelectedValue which is invalid because it does not exist in the list of items.

回答1:


Safest way to set SelectedItem of a DropdownList is to set the SelectedIndex like this:

ds.SelectedIndex = ds.Items.IndexOf(ds.Items.FindByValue(user.user_id.ToString()));


来源:https://stackoverflow.com/questions/21968178/change-the-selected-value-of-a-dropdownlist-inside-nested-repeater

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!