Dear Sir,
I'm Trying to Update MSACCESS database via dapper using DataGridView with CheckBox not updated to database.
There is only one problem if I only update in TXTTIME. Text with TXTOTHERS1. Text and TXTOTHERS2 is empty so it is not updating to the database.
Link sample database MS ACCESS
Is there anything wrong with the code, please guide me
previous link
Thanks
Imports System.ComponentModel
Imports System.Data.OleDb
Imports Dapper
Public Class Form1
Private _criteriasBindingList As New SortableBindingList(Of Person)()
Private bindingSource As BindingSource = Nothing
Dim PersonService As New PersonService()
Public Function GetOledbConnectionString() As String
Return "Provider=Microsoft.ACE.OLEDB.16.0;Data Source=|DataDirectory|\Person.accdb;Persist Security Info=False;"
End Function
Sub New()
InitializeComponent()
Dim CheckedBoxColumn As New DataGridViewCheckBoxColumn
CheckedBoxColumn.Width = 40
CheckedBoxColumn.Name = "checkboxcolumn"
CheckedBoxColumn.HeaderText = "Check"
CheckedBoxColumn.ReadOnly = False
DataGridView1.Columns.Insert(0, CheckedBoxColumn)
End Sub
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles BtnUpdate.Click
Try
_criteriasBindingList = New SortableBindingList(Of Person)(CType(bindingSource.DataSource, IList(Of Person)))
Dim i As Integer = 0
If _criteriasBindingList.Count > 0 Then
For Each row2 As DataGridViewRow In DataGridView1.Rows
Dim isselect As Boolean = Convert.ToBoolean(row2.Cells("checkboxcolumn").Value)
If isselect Then
Dim person As Person = _criteriasBindingList(row2.Index)
Dim update = New Person With {
.TIME = TXTTIME.Text,
.OTHERS1 = TXTOTHERS1.Text,
.OTHERS2 = TXTOTHERS2.Text,
.NAMEPERSON = person.NAMEPERSON,
.DATE = person.DATE,
.IDKEY = person.IDKEY}
PersonService.UpdatePerson(update)
_criteriasBindingList(row2.Index).TIME = TXTTIME.Text
' Checking Other1 TextBox.
If Not String.IsNullOrEmpty(TXTOTHERS1.Text) Then
_criteriasBindingList(row2.Index).OTHERS1 = TXTOTHERS1.Text
End If
' Checking Other2 TextBox.
If Not String.IsNullOrEmpty(TXTOTHERS2.Text) Then
_criteriasBindingList(row2.Index).OTHERS2 = TXTOTHERS2.Text
End If
End If
Next row2
bindingSource = New BindingSource With {.DataSource = _criteriasBindingList}
DataGridView1.DataSource = bindingSource
MessageBox.Show("Person In successfully updated")
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Myapp", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
loaddata()
End Sub
Private Sub loaddata()
_criteriasBindingList = New SortableBindingList(Of Person)(CType(PersonService.GetPERSON(), IList(Of Person)))
bindingSource = New BindingSource With {.DataSource = _criteriasBindingList}
DataGridView1.DataSource = bindingSource 'Set the data source.
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
End Sub
Private Sub myFilter(str1 As String, str2 As String)
loaddata()
If (String.IsNullOrEmpty(str1) AndAlso String.IsNullOrEmpty(str2)) Then
bindingSource.DataSource = _criteriasBindingList
ElseIf (String.IsNullOrEmpty(str1)) Then
bindingSource.DataSource = _criteriasBindingList.Where(Function(c) c.DATE.ToString("dd-MM-yyyy").Contains(str2)).ToList()
ElseIf (String.IsNullOrEmpty(str2)) Then
bindingSource.DataSource = _criteriasBindingList.Where(Function(c) c.NAMEPERSON.ToLower().Contains(str1)).ToList()
Else
bindingSource.DataSource = _criteriasBindingList.Where(Function(c) c.NAMEPERSON.ToLower().Contains(str1) AndAlso c.DATE.ToString("dd-MM-yyyy").Contains(str2)).ToList()
End If
End Sub
Private Sub TextBox1_keyup(sender As Object, e As KeyEventArgs) Handles TXTNAME.KeyUp
Dim str1 = TXTNAME.Text.Trim().ToLower()
Dim str2 = TXTDATE.Text.Trim().ToLower().Replace("/ /", "")
myFilter(str1, str2)
End Sub
Private Sub TextBox2_keyup(sender As Object, e As KeyEventArgs) Handles TXTDATE.KeyUp
Dim str1 = TXTNAME.Text.Trim().ToLower()
Dim str2 = TXTDATE.Text.Trim().ToLower().Replace("/ /", "")
myFilter(str1, str2)
End Sub
End Class
Public Class Person
Public Property NAMEPERSON As String
Public Property AGE As Integer
Public Property [POSITION] As String
Public Property [DATE] As DateTime
Public Property DAYS As String
Public Property TIME() As String
Public Property OTHERS1 As String
Public Property OTHERS2 As String
Public Property IDKEY As Integer
End Class
Public Class PersonService
Public Function GetOledbConnectionString() As String
Return "Provider=Microsoft.ACE.OLEDB.16.0;Data Source=|DataDirectory|\Person.accdb;Persist Security Info=False;"
End Function
Private ReadOnly _conn As OleDbConnection
Private _connectionString As String = GetOledbConnectionString()
Public Sub New()
_conn = New OleDbConnection(_connectionString)
End Sub
Public Function GetPERSON() As IEnumerable(Of Person)
Dim sql = "SELECT PERSON.ID AS [ID],MASTERID.NAMEPERSON AS [NAMEPERSON],PERSON.AGE AS [AGE],[PERSON.POSITION] AS [POSITION],PERSON.DATE AS [DATE],format(PERSON.DATE,'dddd') AS [DAYS],PERSON.TIME AS [TIME],PERSON.Others1 AS [OTHERS1],PERSON.Others2 AS [OTHERS2],PERSON.Others3 AS [OTHERS3] FROM PERSON INNER JOIN MASTERID ON PERSON.ID = MASTERID.ID"
Using _conn = New OleDbConnection(GetOledbConnectionString())
Return _conn.Query(Of Person)(sql).ToList()
End Using
End Function
Public Sub UpdatePerson(ByVal Obj As Person)
Dim sql = String.Empty
If Not String.IsNullOrEmpty(Obj.OTHERS1) AndAlso Not String.IsNullOrEmpty(Obj.OTHERS2) Then
sql = $"UPDATE PERSON INNER JOIN MASTERID ON (PERSON.ID = MASTERID.ID) Set PERSON.TIME = '{Obj.TIME}', PERSON.OTHERS1 = '{Obj.OTHERS1}', PERSON.OTHERS2 = '{Obj.OTHERS2}' WHERE MASTERID.NAMEPERSON = '{Obj.NAMEPERSON}' AND PERSON.DATE = #{Obj.DATE}# AND PERSON.IDKEY = {Obj.IDKEY};"
ElseIf Not String.IsNullOrEmpty(Obj.OTHERS1) Then
sql = $"UPDATE PERSON INNER JOIN MASTERID ON (PERSON.ID = MASTERID.ID) Set PERSON.TIME = '{Obj.TIME}',PERSON.OTHERS1 = '{Obj.OTHERS1}' WHERE MASTERID.NAMEPERSON = '{Obj.NAMEPERSON}' AND PERSON.DATE = #{Obj.DATE}# AND PERSON.IDKEY = {Obj.IDKEY};"
ElseIf Not String.IsNullOrEmpty(Obj.OTHERS2) Then
sql = $"UPDATE PERSON INNER JOIN MASTERID ON (PERSON.ID = MASTERID.ID) Set PERSON.TIME = '{Obj.TIME}',PERSON.OTHERS2 = '{Obj.OTHERS2}' WHERE MASTERID.NAMEPERSON = '{Obj.NAMEPERSON}' AND PERSON.DATE = #{Obj.DATE}# AND PERSON.IDKEY = {Obj.IDKEY};"
End If
' If query is generated call the Dapper Execute method.
If Not String.IsNullOrEmpty(sql) Then
Using _conn = New OleDbConnection(GetOledbConnectionString())
_conn.Execute(sql)
End Using
End If
End Sub
End Class
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
''' <summary>
''' Provides a generic collection that supports data binding and additionally supports sorting.
''' See http://msdn.microsoft.com/en-us/library/ms993236.aspx
''' If the elements are IComparable it uses that; otherwise compares the ToString()
''' </summary>
''' <typeparam name="T">The type of elements in the list.</typeparam>
Public Class SortableBindingList(Of T As Class)
Inherits BindingList(Of T)
Private _isSorted As Boolean
Private _sortDirection As ListSortDirection = ListSortDirection.Ascending
Private _sortProperty As PropertyDescriptor
''' <summary>
''' Initializes a new instance of the <see cref="SortableBindingList{T}"/> class.
''' </summary>
Public Sub New()
End Sub
''' <summary>
''' Initializes a new instance of the <see cref="SortableBindingList{T}"/> class.
''' </summary>
''' <param name="list">An <see cref="T:System.Collections.Generic.IList`1" /> of items to be contained in the <see cref="T:System.ComponentModel.BindingList`1" />.</param>
Public Sub New(ByVal list As IList(Of T))
MyBase.New(list)
End Sub
''' <summary>
''' Gets a value indicating whether the list supports sorting.
''' </summary>
Protected Overrides ReadOnly Property SupportsSortingCore As Boolean
Get
Return True
End Get
End Property
''' <summary>
''' Gets a value indicating whether the list is sorted.
''' </summary>
Protected Overrides ReadOnly Property IsSortedCore As Boolean
Get
Return _isSorted
End Get
End Property
''' <summary>
''' Gets the direction the list is sorted.
''' </summary>
Protected Overrides ReadOnly Property SortDirectionCore As ListSortDirection
Get
Return _sortDirection
End Get
End Property
''' <summary>
''' Gets the property descriptor that is used for sorting the list if sorting is implemented in a derived class; otherwise, returns null
''' </summary>
Protected Overrides ReadOnly Property SortPropertyCore As PropertyDescriptor
Get
Return _sortProperty
End Get
End Property
''' <summary>
''' Removes any sort applied with ApplySortCore if sorting is implemented
''' </summary>
Protected Overrides Sub RemoveSortCore()
_sortDirection = ListSortDirection.Ascending
_sortProperty = Nothing
_isSorted = False 'thanks Luca
End Sub
''' <summary>
''' Sorts the items if overridden in a derived class
''' </summary>
''' <param name="prop"></param>
''' <param name="direction"></param>
Protected Overrides Sub ApplySortCore(ByVal prop As PropertyDescriptor, ByVal direction As ListSortDirection)
_sortProperty = prop
_sortDirection = direction
Dim list As List(Of T) = TryCast(Items, List(Of T))
If list Is Nothing Then
Return
End If
list.Sort(AddressOf Compare)
_isSorted = True
'fire an event that the list has been changed.
OnListChanged(New ListChangedEventArgs(ListChangedType.Reset, -1))
End Sub
Private Function Compare(ByVal lhs As T, ByVal rhs As T) As Integer
Dim result = OnComparison(lhs, rhs)
'invert if descending
If _sortDirection = ListSortDirection.Descending Then
result = -result
End If
Return result
End Function
Private Function OnComparison(ByVal lhs As T, ByVal rhs As T) As Integer
Dim lhsValue As Object = If(lhs Is Nothing, Nothing, _sortProperty.GetValue(lhs))
Dim rhsValue As Object = If(rhs Is Nothing, Nothing, _sortProperty.GetValue(rhs))
If lhsValue Is Nothing Then
Return If(rhsValue Is Nothing, 0, -1) 'nulls are equal
End If
If rhsValue Is Nothing Then
Return 1 'first has value, second doesn't
End If
If TypeOf lhsValue Is IComparable Then
Return DirectCast(lhsValue, IComparable).CompareTo(rhsValue)
End If
If lhsValue.Equals(rhsValue) Then
Return 0 'both are the same
End If
'not comparable, compare ToString
Return lhsValue.ToString().CompareTo(rhsValue.ToString())
End Function
End Class