Thursday, December 23, 2010

What is the DataField Name of a GridView bound to a String Array?

This is a special case that I don’t remember experiencing before but resolved with the help of a StackOverflow question Binding an ASP.NET GridView Control to a string array.

In a simple Asp.Net Membership management application I was simply binding a Role list to a GridView so I could click a link to see which users were members of a selected Role. I was using the following syntax in the CodeBehind where grvRoles is the GridView:

grvRoles.DataSource = Roles.GetAllRoles
grvRoles.DataBind()

Note: Roles.GetAllRoles() is in the System.Web.Security namespace which returns a string array of Roles from the aspnetdb Membership Database.


On the Designer:



<asp:GridView ID="grvRoles" runat="server" 
    EnableModelValidation="True">
    <Columns>
        <asp:CommandField ShowSelectButton="True" />
    </Columns>
</asp:GridView>

Which produced the following output with the GridView auto-generated columns. Notice the column name is “Item”, but imagethe datasource is a string array which doesn’t technically have a DataField name like if it was bound to a Generic List or Collection of class objects.


I want to use a LinkButton where the CommandArgument is the Role name which is represented as a String value of the array. So If I convert the “Select” Command button column to a Template field, what do I use as the DataField name? Generally I would use the syntax:



<asp:GridView ID="GridView1" runat="server" 
    EnableModelValidation="True">
    <Columns>
    <asp:TemplateField ShowHeader="False">
        <ItemTemplate>
            <asp:LinkButton ID="lnkMembers" 
                runat="server" CausesValidation="False"
                CommandArgument='<%#Eval("Item") %>' 
                CommandName="Select" Text="Members"></asp:LinkButton>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>

 

Note the CommandArgument=’<%#Eval(“Item”) %>’, but that won’t work, because the String Array doesn’t actually have an Item property. Instead you can use the longhand syntax: CommandArgument='<%# container.dataitem %>'.

 

If I don’t want to have the GridView auto-generate the columns, what do I use for the asp:BoundField name? Apparently there is a secret syntax by using an exclamation point <asp:BoundField DataField="!" HeaderText="Role" />.

No comments: