我有一个绑定到某些项目的下拉列表。我想用文本框值替换所选项目,并再次想要将下拉列表与新值绑定。 为此,我目前将下拉列表项存储在临时列表中。如何用文本框值替换当前选定的项目。
for (int i = 0; i < DropDownEmail.Items.Count; i++)
{
if (?)
{
ObjRegistration = new ClassRegistration();
ObjRegistration.UserName = TextBoxEmail.Text;
tempEmailList.Add(ObjRegistration)
}
else{
ObjRegistration = new ClassRegistration();
ObjRegistration.UserName = DropDownEmail.Items[i].Text;
tempEmailList.Add(ObjRegistration);
}
}
答案 0 :(得分:1)
您的代码现在写的没有多大意义,但一般来说,如果您想要替换下拉列表中的项目,您需要执行以下操作:
var selectedItem = tempEmailList.SelectedItem; //returns a ListItem object
selectedItem.Text=txtField.Text;
dropDownList.DataBind(); //Rebind it so you see the change.
在您的情况下,您似乎绑定到ClassRegistration
的自定义集合,但由于您在代码隐藏时执行此操作,因此一旦您将元素首次绑定到下拉列表,您只能在下拉列表中引用Items
集合,它们都是ListItem
类型。
您也可以更新基础自定义集合并将其重新绑定到下拉列表中:
var tempEmailList= ... //get it from DB or whatever
tempEmailList.Find(x => x.ID == int.Parse(ddl.SelectedItem.Value)).UserName = txtBox.Text;
ddl.DataSource = tempEmailList;//re-assing the datasource
ddl.DataBind();//rebind