我尝试从c#代码中更改下拉列表选定值:
<repeater >
<repeater>
<dropdown>
我将aspx页面中的数据源添加到下拉列表中 每件事都很好..但我想改变下拉列表的选定值 能够在编辑表时向用户显示先前选择的名称
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();
}
我将此方法添加到转发器的Onload: 但没有任何改变,以前的名字没有显示
P.S:用户对象正确且user.user_id也正确 P.S 2:我试图添加一个ds.DataBind();在更改所选内容但发出错误后:
System.ArgumentOutOfRangeException: 'userdropdown' has a SelectedValue which is invalid because it does not exist in the list of items.
答案 0 :(得分:0)
设置SelectedItem
DropdownList
的最安全方法是设置SelectedIndex
,如下所示:
ds.SelectedIndex = ds.Items.IndexOf(ds.Items.FindByValue(user.user_id.ToString()));