Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use DisplayNameAttribute in ASP.NET

Tags:

asp.net

I want to bind a List to a GridView on a web page, but override the way the property names display via annotation. I thought System.ComponentModel would work, but this doesn't seem to work. Is this only meant for Windows Forms?:

using System.ComponentModel;

namespace MyWebApp
{
    public class MyCustomClass
    {
        [DisplayName("My Column")]
        public string MyFirstProperty
        {
            get { return "value"; }
        }

    public MyCustomClass() {}
}

Then on the page:

protected void Page_Load(object sender, EventArgs e)
{
    IList<MyCustomClass> myCustomClasses = new List<MyCustomClass>
    {
        new MyCustomClass(),
        new MyCustomClass()
    };

TestGrid.DataSource = myCustomClasses;
TestGrid.DataBind();

}

This renders with "MyFirstProperty" as the column header rather than "My Column." Isn't this supposed to work?

like image 329
jlembke Avatar asked Apr 02 '09 22:04

jlembke


1 Answers

When using .net 4 or later you can use gridview1.enabledynamicdata(typeof(mytype)). I haven't looked at all the types you can use there but I know the [displayname("somename")] works well but the [browsable(false)] doesn't omit the column from the grid. It looks like a knit one slip one from MS. at least you can easily rename column names and to omit a column I just declare a variable instead of using a property. It has the same effect...

Just by the way, using the designer to create columns is the easy way out but to just show a different column name takes way to much time especially with classes with many fields.

like image 83
Stanley Gillmer Avatar answered Oct 18 '22 08:10

Stanley Gillmer