C# · 3月 27, 2022

c# – 在ListView中加载Databind DropDownList

我有一个ListView控件,其中包含ItemTemplate标记内的DropDownList控件.
我正在尝试使用ListView控件的ItemCommand事件中的以下代码将现有列表项加载到DropDownList:

DropDownList ddlItem = (DropDownList)e.Item.FindControl(“ddlItem”);con.open();sqlCommand cmd = new sqlCommand();cmd.Connection = con;cmd.CommandText = “SELECT ID,Name FROM Items”;sqlDataReader data = cmd.ExecuteReader();ddlItem.DataSouce = data;ddlItem.DataTextField = “Name”;ddlItem.DataValueField = “ID”;ddlItem.DataBind();con.Close();

绑定项目后,我想根据数据库记录选择所选项目.

我错过了什么吗?

解决方法 您应该在ListView的ItemDataBound事件中执行此操作.您将通过e.Item.FindControl(“ddlItem”)在那里找到DropDownList,通过e.Item.DataItem获取该项的基础数据源.如果您不确定类型,请使用调试器.

protected void ListView1_ItemDataBound(Object sender,ListViewItemEventArgs e){ if (e.Item.ItemType == ListViewItemType.DataItem) { DropDownList ddlItem = (DropDownList) e.Item.FindControl(“ddlItem”); var rowView = e.Item.DataItem as DaTarowView; int id = (int)rowView[“ID”]; // whatever // get data from id … //ddlItem.DataSouce = data; //ddlItem.DataTextField = “Name”; //ddlItem.DataValueField = “ID”; //ddlItem.DataBind(); }}