1

I use grid view in my project to display data.

I display to properties:

<asp:GridView ItemType="WebUI.FeatureInfoArea.FeatureDesc" AutoGenerateColumns="false" ID="gvFeatList" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <%# Item.Title %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <%# Item.Tip %>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

And here how I bind to data source:

FeaturesDesc result = getData();

gvFeatList.DataSource = result.featureDesc;
gvFeatList.DataBind();

And here is FeaturesDesc class:

public class FeaturesDesc
{
    public List<FeatureDesc> featureDesc { get; set; }
}

public class FeatureDesc
{
    public string Title { get; set; }
    public string Tip { get; set; }
    public string UID { get; set; }
} 

When columns is created on browser the data is displayed in rows, but headers of the columns are empty.

I know that I can use TextHeader attribute in TemplateField but I want that column header to be displayd dynamically according to FeatureDesc class property.

How can I make display column's header dynamically?

Michael
  • 13,950
  • 57
  • 145
  • 288
  • AutoGenerateColumns indicate whether bound fields are automatically created for each field in the data source. AutoGenerateColumns="false" means creating **custom columns** and you have to do it manually. – Simon Aug 15 '18 at 09:32

1 Answers1

0

You can use Reflection to get the name of a property as seen here: Get string name of property using reflection. It uses a method for extracting the name of a Property.

string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
    return (propertyExpression.Body as MemberExpression).Member.Name;
}

And then use it like this like my answer in your other question.

GridView1.HeaderRow.Cells[0].Text = GetPropertyName(() => featureDesc[0].Title);

You can also get a single object from the List and use nameof

var feature = featureDesc[0];

GridView1.HeaderRow.Cells[1].Text = nameof(feature.Tip);
VDWWD
  • 35,079
  • 22
  • 62
  • 79