在gridview模板字段中绑定IEnumerable列

时间:2013-06-17 15:12:06

标签: c# asp.net .net-3.5

我有以下设置

ASPX:

<asp:GridView runat="server" ID="gridRepresentatives" AllowPaging="True" DataKeyNames="Id" OnRowCommand="BtnSubmitCommand" OnRowCreated="GridRepresentativesCreated" CssClass="grid" AutoGenerateColumns="False" Width="100%" EmptyDataText="You don't have rights to manage any organisations.">
    <Columns>
        <asp:BoundField DataField="Position" HeaderText="Position"/>
        <asp:BoundField DataField="Name" HeaderText="Name"/>
        <asp:BoundField DataField="Address" HeaderText="Address"/>
        <asp:TemplateField HeaderText="Roles">
            <ItemTemplate>
                <asp:DropDownList runat="server" ID="dropdownRoles" DataMember="Roles" Width="205px">    
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Action">
            <ItemTemplate>
                <asp:DropDownList runat="server" ID="dropdownActions" Width="100px">
                    <asp:ListItem Text="Edit" Value="0"></asp:ListItem>
                    <asp:ListItem Text="Remove" Value="1"></asp:ListItem>
                </asp:DropDownList>
                <asp:Button runat="server" CommandName="Submit" ID="btnSubmit" Text="Go"/>
            </ItemTemplate>
            <ItemStyle CssClass="grid-actions"></ItemStyle>
        </asp:TemplateField>
    </Columns>
    <AlternatingRowStyle CssClass="alternate"></AlternatingRowStyle>
</asp:GridView>

背后的代码:

 var client = new RepresentativeManagementServiceClient();
            try
            {
                IEnumerable<Representative> representatives =     client.ListRepresentatives("01", _organisationId, role);
                gridRepresentatives.DataSource = representatives;
                gridRepresentatives.DataBind();
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text = ex.Message;
                return;
            }
            finally
            {
                client.Close();
            }

gridview绑定到具有公共属性集的Type Represenative的IEnumerable。我想将IEnumerable Roles属性绑定到gridview模板字段内的下拉列表中。我试图将Datamember设置为属性的名称(角色),但它只是不绑定并且不会抛出任何错误。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

您想要为该下拉列表绑定数据源:

<asp:TemplateField HeaderText="Roles">
    <ItemTemplate>
        <asp:DropDownList runat="server" ID="dropdownRoles" DataSource='<%# Eval("Roles") %>' Width="205px">    
        </asp:DropDownList>
    </ItemTemplate>
</asp:TemplateField>

答案 1 :(得分:0)

您应该设置DropDownList的SelectedValue属性。 Intellisence不会出于某种原因显示它,但您可以像这样使用它

    <asp:TemplateField HeaderText="Roles">
        <ItemTemplate>
            <asp:DropDownList runat="server" SelectedValue='<%# Eval("Roles") %>'>    
            </asp:DropDownList>
        </ItemTemplate>
    </asp:TemplateField>

但在绑定它之前,你应该用可能的值填充DropDown。 Manualy或使用一些 数据源(我认为ObjectDataSource对你来说会很好)

相关问题