Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Adding another attribute and checking value for DisplayName

Posted on 2016-08-01
3
Medium Priority
?
107 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 35

Accepted Solution

by:
it_saige earned 2000 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

Independent Software Vendors: 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

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…
Simulator games are perfect for generating sample realistic data streams, especially for learning data analysis. It is even useful for demoing offerings such as Azure stream analytics, PowerBI etc.
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Loops Section Overview
Suggested Courses

782 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