Question

I have a ListView control that contains a DropDownList control inside the ItemTemplate tag. I am trying to load the existing list items to the DropDownList using the codes below inside the ItemCommand event of the ListView control:

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();

After binding the items, I want to choose the selected items based from the database records.

Am I missing something?

Was it helpful?

Solution

You should do that in the ListView's ItemDataBound event instead. You will find your DropDownList there via e.Item.FindControl("ddlItem") get the underlying datasource for that item via e.Item.DataItem. Use the debugger if you're unsure about the types.

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();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top