?
Solved

vb.net / trigger function

Posted on 2016-08-11
3
Medium Priority
?
81 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
[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
3 Comments
 
LVL 40

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 34

Accepted Solution

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

Want to be a Web Developer? Get Certified Today!

Enroll in the Certified Web Development Professional course package to learn HTML, Javascript, and PHP. Build a solid foundation to work toward your dream job!

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
Suggested Courses

762 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