Solved

Adding another attribute and checking value for DisplayName

Posted on 2016-08-01
3
79 Views
Last Modified: 2016-08-18
This is practically the same question I posted last week about the Required Attribute but now I have another Attribute called DisplayName along with my RequiredAttribute and I want to check the Display Name I have set for it, via this attribute, and use that as my column header. I have a loop through my source data, check the attribute and set the header/column name. Can I do that in the RowDataBound like I did with the Required attribute? I tried adding another Where to the statement that was sent me but to no avail. Here is the code that fixed my Required attribute question and in bold is where I tried to add the DisplayName attribute, but its not working?

 Protected Sub GridView_RowDataBound(sender As Object, e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim grid = DirectCast(sender, GridView)
            Dim notRequired = (From [property] In e.Row.DataItem.GetType().GetProperties()
                            Where CType([property].GetCustomAttributes(GetType(RequiredAttribute), False), RequiredAttribute()).Count <= 0
                          [b]  'Tried adding this to check for DisplayName just like the line above it checks for Required attribute???[/b]
                            Where CType([property].GetCustomAttributes(GetType(DisplayAttribute), False), DisplayAttribute()).Count <= 0 
                            Select e.Row.DataItem.GetType().GetProperties().ToList().IndexOf([property]))

            For Each index In notRequired
                If e.Row.Cells.Count - 1 > index Then
                    e.Row.Cells(index).Visible = False
                End If

                If grid.HeaderRow.Cells.Count - 1 > index Then
                    grid.HeaderRow.Cells(index).Visible = False
                End If
            Next

        End If
    End Sub

Open in new window

0
Comment
Question by:jknj72
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 34

Accepted Solution

by:
it_saige earned 500 total points
ID: 41737761
This should accomplish what you are after.

Default.aspx -
<%@ Page Title="Home Page" Language="VB" AutoEventWireup="true" CodeBehind="Default.aspx.vb" Inherits="EE_Q28960739._Default" %>
<form id="form1" runat="server">
	<asp:GridView ID="GridView1" runat="server">
	</asp:GridView>
</form>

Open in new window

Default.aspx.vb -
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations

Public Class _Default
	Inherits Page

	ReadOnly people As New List(Of Person)(From i In Enumerable.Range(0, 10) Select New Person() With {.ID = i, .Name = String.Format("Person{0}", i), .Birthdate = New DateTime(1975, 1, 27).AddMonths(i), .Address = String.Format("12{0} E Street", i)})

	Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
		GridView1.DataSource = people
		GridView1.DataBind()
	End Sub

	Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
		If e.Row.DataItem IsNot Nothing Then
			Dim grid = DirectCast(sender, GridView)
			Dim columns = (From [property] In e.Row.DataItem.GetType().GetProperties()
						Let Headers = CType([property].GetCustomAttributes(GetType(DisplayNameAttribute), False), DisplayNameAttribute()).ToList()
						Select New With
							  {
								  .Index = e.Row.DataItem.GetType().GetProperties().ToList().IndexOf([property]),
								  .Header = If(Headers.Count > 0, Headers(0).DisplayName, Nothing),
								  .IsRequired = CType([property].GetCustomAttributes(GetType(RequiredAttribute), False), RequiredAttribute()).Count > 0
							  }
						  )

			For Each column In columns
				If e.Row.Cells.Count > column.Index Then
					e.Row.Cells(column.Index).Visible = column.IsRequired
				End If

				If grid.HeaderRow.Cells.Count > column.Index Then
					If column.Header IsNot Nothing AndAlso Not String.IsNullOrWhiteSpace(column.Header) Then
						grid.HeaderRow.Cells(column.Index).Text = column.Header
					End If
					grid.HeaderRow.Cells(column.Index).Visible = column.IsRequired
				End If
			Next
		End If
	End Sub
End Class

Class Person
	<Required> _
	<DisplayName("Person is in the Table with ID")> _
	Public Property ID() As Integer
	<Required> _
	Public Property Name() As String
	Public Property Address() As String
	<Required> _
	<DisplayName("Person Was Born On This Date")> _
	Public Property Birthdate() As DateTime
	Public Property Hobbies() As List(Of String)
End Class

Open in new window

Default.aspx.designer.vb -
'------------------------------------------------------------------------------
' <auto-generated>
'     This code was generated by a tool.
'
'     Changes to this file may cause incorrect behavior and will be lost if
'     the code is regenerated. 
' </auto-generated>
'------------------------------------------------------------------------------

Option Strict On
Option Explicit On


Partial Public Class _Default

	'''<summary>
	'''form1 control.
	'''</summary>
	'''<remarks>
	'''Auto-generated field.
	'''To modify move field declaration from designer file to code-behind file.
	'''</remarks>
	Protected WithEvents form1 As Global.System.Web.UI.HtmlControls.HtmlForm

	'''<summary>
	'''GridView1 control.
	'''</summary>
	'''<remarks>
	'''Auto-generated field.
	'''To modify move field declaration from designer file to code-behind file.
	'''</remarks>
	Protected WithEvents GridView1 As Global.System.Web.UI.WebControls.GridView
End Class

Open in new window

Produces the following output -Capture.JPG-saige-
0
 

Author Comment

by:jknj72
ID: 41744096
sorry im so late with the answer. I got assigned to something else and I will check this today....Thanks for your patience
0
 

Author Closing Comment

by:jknj72
ID: 41761241
This works great and I apologize for not answering back sooner but I got pulled off this project. But what you gave me works great. I have another question regarding this so I hope you can take a look. Thanks again for your help
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

732 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question