C#如何访问listview中的下拉框?
-
05-07-2019 - |
题
我有一个列表视图。在我的listview中,我有一个下拉框,我想填写我的代码隐藏页面。唯一的问题是,我不知道如何访问这个webcontrol。以下不起作用:
DropDownList ddl = (DropDownList)lvUserOverview.Controls[0];
我知道索引是0,因为下拉列表是listview上唯一的控件(当我尝试索引1时,我得到索引超出范围异常)。
有人可以告诉我如何访问下拉列表吗?在我的pagebehind中,我想添加listitems。
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()));
}
}
解决方案
要获取其自己的Load事件处理程序内的下拉列表的句柄,您需要做的就是将发送者强制转换为DropDownList。
DropDownList ddlRole = sender as DropDownList;
其他提示
如果这是在ListView中呈现的话,那么有可能会实例化多个DropDownLists,每个DropDownLists都会获得一个唯一的ID,你将无法使用Matthew的方法。
您可能希望使用ItemDataBound事件来访问e.Item.FindControl(&quot; NameOfDropDownList&quot;),这将允许您对创建的每个下拉列表进行迭代。
如果你只创建一个......为什么它在ListView中?
试试这个:
DropDownList ddl = (DropDownList)lvUserOverview.FindControl("NameOfDropDownList");
如果您的控件是数据绑定的,请确保在数据绑定后尝试访问其后代。我也可以帮助在该行之前检查调试器中的对象。
不隶属于 StackOverflow