Solved

Adding another attribute and checking value for DisplayName

Posted on 2016-08-01
3
90 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
In this video, viewers will be given step by step instructions on adjusting mouse, pointer and cursor visibility in Microsoft Windows 10. The video seeks to educate those who are struggling with the new Windows 10 Graphical User Interface. Change Cu…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

627 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