C# 如何访问列表视图中的下拉框?
我有一个列表视图。 在我的列表视图中,我有一个下拉框,我想填写我的代码隐藏页面。 唯一的问题是,我不知道如何访问这个网络控件。 以下不起作用:
DropDownList ddl = (DropDownList)lvUserOverview.Controls[0];
我知道索引为 0,因为下拉列表是列表视图上的唯一控件(此外,当我尝试索引 1 时,我得到索引超出范围异常)。
有人可以告诉我如何访问下拉列表吗? 在我的页面后面,我想添加列表项。
ASPX 代码:
<asp:DropDownList ID="ddlRole" onload="ddlRole_Load" runat="server">
</asp:DropDownList>
隐藏代码:
protected void ddlRole_Load(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)lvUserOverview.FindControl("ddlRole");
if (ddl != null)
{
foreach (Role role in roles)
ddl.Items.Add(new ListItem(role.Description, role.Id.ToString()));
}
}
I have a listview. In my listview I have a dropdownbox which I want to fill in my codebehind page. Only the thing is, I don't know how to access this webcontrol. The following doesn't work:
DropDownList ddl = (DropDownList)lvUserOverview.Controls[0];
I know the index is 0 because the dropdownlist is the only control on the listview (also when I try index 1 I get a index out of range exception).
Can someone tell me how i can access the dropdownlist? In my pagebehind I want to add listitems.
ASPX Code :
<asp:DropDownList ID="ddlRole" onload="ddlRole_Load" runat="server">
</asp:DropDownList>
Codebehind:
protected void ddlRole_Load(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)lvUserOverview.FindControl("ddlRole");
if (ddl != null)
{
foreach (Role role in roles)
ddl.Items.Add(new ListItem(role.Description, role.Id.ToString()));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果这是在 ListView 中呈现的,那么有可能会实例化多个 DropDownList,每个 DropDownList 都会获得一个唯一的 ID,并且您将无法使用 Matthew 的方法。
您可能希望使用 ItemDataBound 事件来访问 e.Item.FindControl("NameOfDropDownList"),这将允许您迭代创建的每个下拉列表。
如果您只创建一个...为什么它在 ListView 中?
If this is being rendered in a ListView then there's a chance that multiple DropDownLists are going to be instantiated, each will get a unique ID and you wouldn't be able to use Matthew's approach.
You might want to use the ItemDataBound event to access e.Item.FindControl("NameOfDropDownList") which will allow you to iterate on each dropdown created.
If you are only creating one... why it is in a ListView?
要获取其自己的 Load 事件处理程序内的下拉列表的句柄,您所需要做的就是将 sender 转换为 DropDownList。
To get a handle to the drop down list inside of its own Load event handler, all you need to do is cast sender as a DropDownList.
尝试这个:
Try this:
如果您的控件是数据绑定的,请确保在数据绑定后尝试访问它们的后代。 我还可以帮助检查该行之前调试器中的对象。
If your controls are data bound, make sure you try to access their descendents after data binding. I may also help just inspecting objects in debugger before that line.