Search code examples
c#asp.net.netdatagridboundcolumn

ASP.NET DataGrid BoundColumn


I have an ASP.NET DataGrid where each row object allows access to its data through the following mechanism: public object this[string fieldName] { get; }. This means that in the XML I need to do something similar and can't just use a PropertyName. This class is third party, so I can't make a Property for it. Is there any syntax to make this work?

<asp:DataGrid ID="test" runat="server" PageSize="25" AllowPaging="True" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundColumn HeaderText="Test" DataField="this['iswhatiwanttodo']">
            </asp:BoundColumn>
        </Columns>
    </asp:DataGrid>

Solution

  • Instead of using the BoundColumn, you can use a TemplateColumn instead. You can then place a label in the column like so:

    <asp:DataGrid ID="test" runat="server" PageSize="25" AllowPaging="True" AutoGenerateColumns="False" OnItemDataBound="test_ItemDataBound">
        <Columns>
            <asp:TemplateColumn HeaderText="Test">
               <ItemTemplate>
                     <asp:Literal ID="litName" runat="server" />
               </ItemTemplate>
            </asp:TemplateColumn>
        </Columns>
    </asp:DataGrid>
    

    You'll notice I also included the event "OnItemDataBound" - which lets you do things in the code behind for the page. From here, you'll want to create an event as follows, and you can get any property you want and set the Literal's text to what you need.

    protected void test_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            Literal name;
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                name = (Literal)e.Item.FindControl("litName");
                name.Text = [Grab Your Property Value Here];
            }
        }