views:

2862

answers:

2

I have a DataGrid that looks like this (slightly simplified here):

<asp:DataGrid ID="grdQuotas" runat="server" AutoGenerateColumns="False">
    <HeaderStyle CssClass="quotas-header" />
    <Columns>
        <asp:TemplateColumn>
            <HeaderTemplate>
                Max order level</HeaderTemplate>
            <ItemTemplate>
                <asp:DropDownList ID="ddlMaxOrderLevel" runat="server" DataSourceID="xdsOrderLevel"
                    DataTextField="Text" DataValueField="Value" SelectedValue='<%# Bind("MaxOrderLevel") %>'>
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:DataGrid>

<asp:XmlDataSource ID="xdsOrderLevel" runat="server" DataFile="~/App_Data/OrderLevels.xml">
</asp:XmlDataSource>

In my Page_Load event handler I am creating a DataTable containing default values and DataBinding it to the DataGrid.

The problem is that this is taking place before the DropDownList ddlMaxOrderLevel has been bound to its DataSource, so I get a runtime error telling me that the SelectedValue cannot be set.

If ddlMaxOrderLevel was not in a DataGrid I could just call DataBind() on it. However I cannot do that in this scenario - since it is in an ItemTemplate.

Can anyone suggest a workaround or alternate approach?

+1  A: 

You could do the Databinding of the DropDownlist in the Databound event of the DataGrid.

Edit: I will give you an example that i have tested:

 protected void dg_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer)
        {
            DropDownList dl = (DropDownList)((DataGridItem)e.Item).FindControl("ddlMaxOrderLevel");

            dl.DataSource = levels;
            dl.DataBind();

            dl.SelectedValue = ((DataRowView)e.Item.DataItem)["number"].ToString();


        }

    }
netadictos
Unfortunately that won't work for the same reason as outlined in my original question: The DropDownList is within an ItemTemplate, so does not exist as an instantiated control that you can reference
Richard Ev
But you can use DataGridItem.FindControl to find the DDL by ID and DataGridItem.DataItem to get the "MaxOrderLevel." Then you can set the list's selected value with the same property that you've currently got in the markup.
Kevin Gorski
Plz tell me if this helped you or if you haved found a better answer
netadictos
A: 

Create another DataSource and bind it to the DataGrid. Where the SelectMethod would return the default values in a simple object.

Then all the binding should happily work together.

BlackMael