我已经对此进行了搜索,但似乎没有达到我需要的确切要求。这是场景:
虽然要求有所变化,但变更涉及以下内容:
那么有没有办法获取File1的ID,这样当ItemDataBound事件触发File2和File3时,它只会更新File1的DropDownList?或者我必须考虑另一种方法来做到这一点?
答案 0 :(得分:1)
在ItemDataBound事件处理程序中,您可以获取对DropDownList的引用并存储在成员变量中。您可以使用该变量来保留对后续ItemDataBound事件的DropDownList的访问。
听起来你需要做这样的事情:
public partial class _Default : System.Web.UI.Page
{
// Dummy data class. We'll bind a list of these to the repeater.
class File
{
public string Name { get; set; }
public int ID { get; set; }
public List<string> AListOfStrings { get; set; }
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
rptrTest.ItemDataBound +=
new RepeaterItemEventHandler(rptrTest_ItemDataBound);
}
private DropDownList file1DropDown;
void rptrTest_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// Find the DropDownList in the repeater's ItemTemplate
// so we can manipulate it.
DropDownList ddlSelect =
e.Item.FindControl("ddlSelect") as DropDownList;
File dataItem = (File)e.Item.DataItem;
DropDownList currentDropDownList;
switch (dataItem.ID)
{
case 1:
// Store the current item's DropDownList for later...
file1DropDown = ddlSelect;
currentDropDownList = file1DropDown;
break;
case 2:
case 3:
currentDropDownList = file1DropDown;
break;
default:
currentDropDownList = ddlSelect;
break;
}
// Get all of the strings starting with the current ID and
// add them to whichever DropDownList we need to modify.
currentDropDownList.Items.AddRange((
from s
in dataItem.AListOfStrings
where s.StartsWith(dataItem.ID.ToString())
select new ListItem(s)).ToArray());
}
protected void Page_Load(object sender, EventArgs e)
{
// Just build up a list of strings which we can filter later.
List<string> stringList = new List<string>();
foreach (string number in (new[] { "1", "2", "3", "4" }))
{
foreach (string letter in (new[] { "a", "b", "c", "d", "e" }))
{
stringList.Add(number + " " + letter);
}
}
List<File> myObjects = new List<File>(new[]
{
new File { ID = 1, Name = "Foo", AListOfStrings = stringList },
new File { ID = 2, Name = "Bar", AListOfStrings = stringList },
new File { ID = 3, Name = "Baz", AListOfStrings = stringList },
new File { ID = 4, Name = "Quux", AListOfStrings = stringList }
});
rptrTest.DataSource = myObjects;
rptrTest.DataBind();
}
}
...你的ASPX页面将包含一个如下所示的转发器:
<asp:Repeater runat="server" ID="rptrTest">
<ItemTemplate>
ID: <%#DataBinder.Eval(Container.DataItem, "ID")%>
<br />
Name: <%#DataBinder.Eval(Container.DataItem, "Name")%>
<br />
Select: <asp:DropDownList runat="server" ID="ddlSelect" />
<br /><br />
</ItemTemplate>
</asp:Repeater>
因此,在代码隐藏文件的rptrTest_ItemDataBound
事件处理程序中,有一个switch语句检查File.ID
以查看它绑定到哪个文件实例。如果ID为1,则DropDownList将分配给file1DropDown
。然后在后续事件中,交换机块其余部分内的逻辑决定我们需要修改哪个DropDownList。