DataBound DropDownList in DataGrid - binding order

I have a DataGrid that looks like this (simplified a bit 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 event handler, Page_Load

I create DataTable

one containing the defaults and DataBind

using it DataGrid

.

The problem is that this happens before the DropDownList

ddlMaxOrderLevel is bound to DataSource

, so I get a runtime error telling me the parameter SelectedValue

could not be set.

If ddlMaxOrderLevel was not in DataGrid

, I could just call DataBind()

on it. However, I cannot do this in this scenario - since it is in ItemTemplate

.

Can anyone suggest a workaround or alternative approach?

0


source to share


2 answers


Create another data source and bind it to the DataGrid. If SelectMethod will return default values ​​in plain object.



Then the whole binding should happily work together.

0


source


You can bind the data to the DropDownlist in the Databound DataGrid event.

Edit: I'll give you an example that I've 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();


        }

    }

      

+1


source







All Articles