Solved

Adding another attribute and checking value for DisplayName

Posted on 2016-08-01
3
48 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
  • 2
3 Comments
 
LVL 32

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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

705 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now