3

ItemTemplate我有一个 ListView 控件,该控件在标记内包含一个 DropDownList 控件。我正在尝试使用ItemCommandListView 控件事件中的以下代码将现有列表项加载到 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();

绑定项目后,我想从数据库记录中选择选定的项目。

我错过了什么吗?

4

1 回答 1

7

您应该改为在ListView'sItemDataBound事件中执行此操作。您将DropDownList通过e.Item.FindControl("ddlItem")获取该项目的基础数据源来找到您所在的位置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();
    }
}
于 2013-11-15T09:19:23.737 回答