Solved

Adding another attribute and checking value for DisplayName

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

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
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…

831 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