Solved

vb.net / trigger function

Posted on 2016-08-11
3
53 Views
Last Modified: 2016-08-16
using vb.net.
Is there a way to trigger a function when the number of rows in a data table is of a certain size or is 0 ? Like I want to call a method if the table has 0 rows.
0
Comment
Question by:Jess31
3 Comments
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 41752729
You would have to hook into the OnDataBound event and also RowDeleted event.  

Fire the trigger from each of those.
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 41752741
>>data table is of a certain size
In addition to the previous comment look at when a row is added as well
0
 
LVL 32

Accepted Solution

by:
it_saige earned 500 total points
ID: 41753106
Not to mention DataBindingCompleted.  You could also implement your own DataGridView that inherits from DataGridView and implement your own events.  Here is an example of the methods discussed herein:

Form1.vb -
Imports System.ComponentModel

Public Class Form1
	Private Sub OnClick(sender As Object, e As EventArgs) Handles btnRemove.Click, btnClear.Click, btnAdd.Click
		If TypeOf sender Is Button Then
			Dim btn = DirectCast(sender, Button)
			If btn.Equals(btnAdd) Then
				If dgvData.DataSource IsNot Nothing AndAlso TypeOf dgvData.DataSource Is IList(Of Person) AndAlso CType(dgvData.DataSource, IList(Of Person)).Count > 0 Then
					Dim data = DirectCast(dgvData.DataSource, List(Of Person))
					dgvData.DataSource = Nothing
					data.AddRange(From i In Enumerable.Range(data.Last().ID + 1, 5) Select New Person() With {.ID = i, .FirstName = String.Format("FirstName{0}", i), .BirthDate = DateTime.Now.AddYears(-(9 * i)), .IsWorking = i Mod 2 = 0})
					dgvData.DataSource = data
				Else
					dgvData.DataSource = (From i In Enumerable.Range(0, 5) Select New Person() With {.ID = i, .FirstName = String.Format("FirstName{0}", i), .BirthDate = DateTime.Now.AddYears(-(9 * i)), .IsWorking = i Mod 2 = 0}).ToList()
				End If
			ElseIf btn.Equals(btnClear) Then
				dgvData.DataSource = Nothing
			ElseIf btn.Equals(btnRemove) Then
				If dgvData.DataSource IsNot Nothing AndAlso TypeOf dgvData.DataSource Is IList(Of Person) AndAlso CType(dgvData.DataSource, IList(Of Person)).Count > 0 Then
					Dim data = DirectCast(dgvData.DataSource, List(Of Person))
					For Each row As DataGridViewRow In dgvData.SelectedRows.Cast(Of DataGridViewRow).Reverse()
						data.Remove(CType(row.DataBoundItem, Person))
					Next
					dgvData.DataSource = Nothing
					dgvData.DataSource = data
				End If
			End If
		End If
	End Sub

	Private Sub OnDataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles dgvData.DataBindingComplete
		If TypeOf sender Is DataGridView Then
			ShowMessage(CType(sender, DataGridView), "DataBinding Completed: ")
		End If
	End Sub

	Private Sub OnLeave(sender As Object, e As EventArgs) Handles nudMin.Leave, nudMax.Leave
		If TypeOf sender Is NumericUpDown Then
			Dim nud = DirectCast(sender, NumericUpDown)
			If nud.Equals(nudMax) Then
				If nud.Value <= nudMin.Value Then
					nud.Value = nudMin.Value + 1
				End If
				dgvData.MaximumRows = nud.Value
			ElseIf nud.Equals(nudMin) Then
				If nud.Value < 0 Then
					nud.Value = 0
				ElseIf nud.Value >= nudMax.Value Then
					nud.Value = nudMax.Value - 1
				End If
				dgvData.MinimumRows = nud.Value
			End If
		End If
	End Sub

	Private Sub OnLoad(sender As Object, e As EventArgs) Handles MyBase.Load
		nudMax.Value = 20
		nudMin.Value = 0
		dgvData.EmptyTextColor = Brushes.Black
		dgvData.MaximumRows = nudMax.Value
		dgvData.MinimumRows = nudMin.Value
	End Sub

	Private Sub OnMaximumRecordsReached(sender As Object, e As EventArgs) Handles dgvData.MaximumRecordsReached
		If TypeOf sender is DataGridView Then
			ShowMessage(CType(sender, DataGridView), String.Format("Maximum Records Reached: "))
		End If
	End Sub

	Private Sub OnRowsAdded(sender As Object, e As DataGridViewRowsAddedEventArgs) Handles dgvData.RowsAdded
		If TypeOf sender Is DataGridView Then
			ShowMessage(CType(sender, DataGridView), String.Format("Adding {0} rows: ", e.RowCount))
		End If
	End Sub

	Private Sub OnRowsRemoved(sender As Object, e As DataGridViewRowsRemovedEventArgs) Handles dgvData.RowsRemoved
		If TypeOf sender Is DataGridView Then
			ShowMessage(CType(sender, DataGridView), String.Format("Removing {0} rows: ", e.RowCount))
		End If
	End Sub

	Private Sub ShowMessage(grid As DataGridView, message As String)
		If grid.Rows.Count < nudMin.Value Then
			MessageBox.Show(String.Format("{0} There are less than {1}; the minimum amount of records...", message, nudMin.Value))
		ElseIf grid.Rows.Count > nudMin.Value AndAlso grid.Rows.Count < nudMax.Value Then
			MessageBox.Show(String.Format("{0} There are more than {1} and less than {2} records...", message, nudMin.Value, nudMax.Value))
		ElseIf grid.Rows.Count > nudMax.Value Then
			MessageBox.Show(String.Format("{0} There are more than {1}; the maximum amount of records...", message, nudMax.Value))
		End If
	End Sub
End Class

Class Person
	Public Property ID() As Integer
	Public Property FirstName() As String
	Public Property BirthDate() As DateTime
	Public Property IsWorking() As Boolean
End Class

Public Delegate Sub MaximumRecordsReachedEventHandler(ByVal sender As Object, ByVal e As EventArgs)
Class DataGridViewEx
	Inherits DataGridView
	Private _emptyTextColor As Brush = Brushes.LightGray
	Private _minimumRows As Integer = 0
	Private _maximumRows As Integer = 50

	Private ReadOnly _maximumRecordsReached As New List(Of MaximumRecordsReachedEventHandler)
	Public Custom Event MaximumRecordsReached As MaximumRecordsReachedEventHandler
		AddHandler(value As MaximumRecordsReachedEventHandler)
			_maximumRecordsReached.Add(value)
		End AddHandler

		RemoveHandler(value As MaximumRecordsReachedEventHandler)
			_maximumRecordsReached.Remove(value)
		End RemoveHandler

		RaiseEvent(sender As Object, e As EventArgs)
			For Each handler As MaximumRecordsReachedEventHandler In _maximumRecordsReached
				Try
					handler.Invoke(sender, e)
				Catch ex As Exception
					Debug.WriteLine(String.Format("Exception while invoking event handler: {0}", ex))
				End Try
			Next
		End RaiseEvent
	End Event

	<Category("Custom"), Description("Displays a message in the DataGridView when no records are displayed in it."), DefaultValue(GetType(String), "")> _
	Public Property EmptyText() As String

	Public Property EmptyTextColor() As Brush
		Get
			Return _emptyTextColor
		End Get
		Set(ByVal value As Brush)
			_emptyTextColor = value
		End Set
	End Property

	<Category("Custom"), Description("If the number of rows in the DataGridView is above this amount, an event is thrown."), DefaultValue(GetType(Integer), "0")> _
	Public Property MaximumRows() As Integer
		Get
			Return _maximumRows
		End Get
		Set(ByVal value As Integer)
			If value <= _minimumRows Then value = _minimumRows + 1
			_maximumRows = value
			Invalidate()
		End Set
	End Property

	<Category("Custom"), Description("If the number of rows in the DataGridView is at or below this amount, a message is displayed."), DefaultValue(GetType(Integer), "0")> _
	Public Property MinimumRows() As Integer
		Get
			Return _minimumRows
		End Get
		Set(ByVal value As Integer)
			If value < 0 Then value = 0
			_minimumRows = value
			Invalidate()
		End Set
	End Property

	Protected Overrides Sub OnRowsAdded(e As DataGridViewRowsAddedEventArgs)
		MyBase.OnRowsAdded(e)
		If Rows.Count > MaximumRows Then
			RaiseEvent MaximumRecordsReached(Me, e)
		End If
	End Sub

	Protected Overrides Sub OnPaint(e As PaintEventArgs)
		MyBase.OnPaint(e)
		If Enabled AndAlso Rows.Count <= MinimumRows AndAlso Not String.IsNullOrWhiteSpace(EmptyText) Then
			Using [graphics] = e.Graphics
				Using [format] = New StringFormat() With {.Alignment = StringAlignment.Center, .LineAlignment = StringAlignment.Center}
					[graphics].DrawString(EmptyText, Font, EmptyTextColor, ClientRectangle, [format])
				End Using
			End Using
		End If
	End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
		Me.dgvData = New EE_Q28962904.DataGridViewEx()
		Me.lblMin = New System.Windows.Forms.Label()
		Me.nudMin = New System.Windows.Forms.NumericUpDown()
		Me.nudMax = New System.Windows.Forms.NumericUpDown()
		Me.lblMax = New System.Windows.Forms.Label()
		Me.btnAdd = New System.Windows.Forms.Button()
		Me.btnClear = New System.Windows.Forms.Button()
		Me.btnRemove = New System.Windows.Forms.Button()
		CType(Me.dgvData, System.ComponentModel.ISupportInitialize).BeginInit()
		CType(Me.nudMin, System.ComponentModel.ISupportInitialize).BeginInit()
		CType(Me.nudMax, System.ComponentModel.ISupportInitialize).BeginInit()
		Me.SuspendLayout()
		'
		'dgvData
		'
		Me.dgvData.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
		Me.dgvData.EmptyText = "There are 0 rows to display..."
		Me.dgvData.Location = New System.Drawing.Point(13, 13)
		Me.dgvData.Name = "dgvData"
		Me.dgvData.RowHeadersVisible = False
		Me.dgvData.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect
		Me.dgvData.Size = New System.Drawing.Size(526, 246)
		Me.dgvData.TabIndex = 0
		'
		'lblMin
		'
		Me.lblMin.AutoSize = True
		Me.lblMin.Location = New System.Drawing.Point(10, 270)
		Me.lblMin.Name = "lblMin"
		Me.lblMin.Size = New System.Drawing.Size(51, 13)
		Me.lblMin.TabIndex = 1
		Me.lblMin.Text = "Minimum:"
		'
		'nudMin
		'
		Me.nudMin.Location = New System.Drawing.Point(70, 268)
		Me.nudMin.Name = "nudMin"
		Me.nudMin.Size = New System.Drawing.Size(44, 20)
		Me.nudMin.TabIndex = 2
		'
		'nudMax
		'
		Me.nudMax.Location = New System.Drawing.Point(180, 268)
		Me.nudMax.Name = "nudMax"
		Me.nudMax.Size = New System.Drawing.Size(44, 20)
		Me.nudMax.TabIndex = 4
		'
		'lblMax
		'
		Me.lblMax.AutoSize = True
		Me.lblMax.Location = New System.Drawing.Point(120, 270)
		Me.lblMax.Name = "lblMax"
		Me.lblMax.Size = New System.Drawing.Size(54, 13)
		Me.lblMax.TabIndex = 3
		Me.lblMax.Text = "Maximum:"
		'
		'btnAdd
		'
		Me.btnAdd.Location = New System.Drawing.Point(242, 265)
		Me.btnAdd.Name = "btnAdd"
		Me.btnAdd.Size = New System.Drawing.Size(97, 23)
		Me.btnAdd.TabIndex = 5
		Me.btnAdd.Text = "Add 5 Records"
		Me.btnAdd.UseVisualStyleBackColor = True
		'
		'btnClear
		'
		Me.btnClear.Location = New System.Drawing.Point(464, 265)
		Me.btnClear.Name = "btnClear"
		Me.btnClear.Size = New System.Drawing.Size(75, 23)
		Me.btnClear.TabIndex = 6
		Me.btnClear.Text = "Clear Grid"
		Me.btnClear.UseVisualStyleBackColor = True
		'
		'btnRemove
		'
		Me.btnRemove.Location = New System.Drawing.Point(345, 265)
		Me.btnRemove.Name = "btnRemove"
		Me.btnRemove.Size = New System.Drawing.Size(113, 23)
		Me.btnRemove.TabIndex = 7
		Me.btnRemove.Text = "Remove Selected"
		Me.btnRemove.UseVisualStyleBackColor = True
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(551, 296)
		Me.Controls.Add(Me.btnRemove)
		Me.Controls.Add(Me.btnClear)
		Me.Controls.Add(Me.btnAdd)
		Me.Controls.Add(Me.nudMax)
		Me.Controls.Add(Me.lblMax)
		Me.Controls.Add(Me.nudMin)
		Me.Controls.Add(Me.lblMin)
		Me.Controls.Add(Me.dgvData)
		Me.Name = "Form1"
		Me.Text = "Form1"
		CType(Me.dgvData, System.ComponentModel.ISupportInitialize).EndInit()
		CType(Me.nudMin, System.ComponentModel.ISupportInitialize).EndInit()
		CType(Me.nudMax, System.ComponentModel.ISupportInitialize).EndInit()
		Me.ResumeLayout(False)
		Me.PerformLayout()

	End Sub
	Friend WithEvents dgvData As DataGridViewEx
	Friend WithEvents lblMin As System.Windows.Forms.Label
	Friend WithEvents nudMin As System.Windows.Forms.NumericUpDown
	Friend WithEvents nudMax As System.Windows.Forms.NumericUpDown
	Friend WithEvents lblMax As System.Windows.Forms.Label
	Friend WithEvents btnAdd As System.Windows.Forms.Button
	Friend WithEvents btnClear As System.Windows.Forms.Button
	Friend WithEvents btnRemove As System.Windows.Forms.Button

End Class

Open in new window

Initial load -Capture.JPG-saige-
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

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…
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…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

757 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

23 Experts available now in Live!

Get 1:1 Help Now