change the selected value of a dropdownlist inside

2019-05-14 07:00发布

问题:

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()));