Hi kana250688,
Please refer the below code.
Code:
C#
public class Form1
{
private List<OrderDetail> OrderDetail;
private BindingSource bindingSource = null/* TODO Change to default(_) if this is not a reference type */;
private SortableBindingList<OrderDetail> _criteriasBindingList = new SortableBindingList<OrderDetail>();
public Form1()
{
InitializeComponent();
this.CenterToScreen();
DataGridViewCheckBoxColumn CheckedBoxColumn = new DataGridViewCheckBoxColumn();
CheckedBoxColumn.Width = 40;
CheckedBoxColumn.Name = "checkboxcolumn";
CheckedBoxColumn.HeaderText = "Check";
CheckedBoxColumn.ReadOnly = false;
DataGridView1.Columns.Insert(0, CheckedBoxColumn);
}
private void Form1_Load(object sender, EventArgs e)
{
this.LoadData();
}
private void LoadData()
{
OrderDetail = new List<OrderDetail>()
{
new OrderDetail()
{
Invono = "PI0001",
InvoDate = Convert.ToDateTime("06-05-2024"),
Days = Convert.ToDateTime("06-05-2024").ToString("dddd"),
ProductName = "TEST 1000",
UnitPrice = 15000,
Quantity = 20
},
new OrderDetail()
{
Invono = "PI0002",
InvoDate = Convert.ToDateTime("07-05-2024"),
Days = Convert.ToDateTime("07-05-2024").ToString("dddd"),
ProductName = "TEST 2000",
UnitPrice = 25000,
Quantity = 20
},
new OrderDetail()
{
Invono = "PI0003",
InvoDate = Convert.ToDateTime("06-05-2024"),
Days = Convert.ToDateTime("06-05-2024").ToString("dddd"),
ProductName = "TEST 3000",
UnitPrice = 17000,
Quantity = 20
},
new OrderDetail()
{
Invono = "PI0004",
InvoDate = Convert.ToDateTime("07-05-2024"),
Days = Convert.ToDateTime("07-05-2024").ToString("dddd"),
ProductName = "TEST 4000",
UnitPrice = 18000,
Quantity = 20
},
new OrderDetail()
{
Invono = "PI0005",
InvoDate = Convert.ToDateTime("06-05-2024"),
Days = Convert.ToDateTime("06-05-2024").ToString("dddd"),
ProductName = "TEST 5000",
UnitPrice = 19000,
Quantity = 20
}
};
_criteriasBindingList = new SortableBindingList<OrderDetail>(OrderDetail);
bindingSource = new BindingSource() { DataSource = _criteriasBindingList };
DataGridView1.DataSource = bindingSource;
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
}
private void myFilter(string idPeople, string InvoDate, string days)
{
LoadData();
IEnumerable<OrderDetail> data = _criteriasBindingList;
if (!string.IsNullOrEmpty(idPeople))
data = data.Where(c => c.ProductName.ToLower().StartsWith(idPeople)).ToList();
if (!string.IsNullOrEmpty(InvoDate))
{
DateTime dt;
bool isValid = DateTime.TryParseExact(InvoDate, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, ref dt);
if (isValid)
data = data.Where(c => c.InvoDate.ToString["dd-MM-yyyy"].Equals(InvoDate)).ToList();
}
if (!string.IsNullOrEmpty(days))
data = data.Where(c => c.Days.ToLower().StartsWith(days)).ToList();
_criteriasBindingList = new SortableBindingList<OrderDetail>((IList<OrderDetail>)data);
bindingSource.DataSource = _criteriasBindingList;
}
private void TXT_FILTER(object sender, KeyEventArgs e)
{
var ProductName = TXTProductName.Text.Trim().ToLower();
var InvoDate = MaskedTextBoxInvoDate.Text.Trim().ToLower();
var days = Txtdays.Text.Trim().ToLower();
myFilter(ProductName, InvoDate, days);
}
private void Button1_Click(object sender, EventArgs e)
{
try
{
_criteriasBindingList = new SortableBindingList<OrderDetail>((IList<OrderDetail>)bindingSource.DataSource);
int i = 0;
if (_criteriasBindingList.Count > 0)
{
foreach (DataGridViewRow row2 in DataGridView1.Rows)
{
bool isselect = Convert.ToBoolean(row2.Cells("checkboxcolumn").Value);
if (isselect)
{
OrderDetail person = _criteriasBindingList(row2.Index);
// Checking InvoDate in MaskedTextBoxInvoDate.
if (MaskedTextBoxInvoDate.Text == " - -")
_criteriasBindingList.Item(i).InvoDate = (DateTime)MaskedTextBox1.Text;
else if (!string.IsNullOrEmpty(MaskedTextBoxInvoDate.Text.Replace("-", "").Trim()))
_criteriasBindingList.Item(i).InvoDate = (DateTime)MaskedTextBox1.Text;
// Checking ProductName in textbox1.
if (!string.IsNullOrEmpty(TXTProductName.Text))
_criteriasBindingList.Item(i).ProductName = TXTProductName.Text;
}
i = i + 1;
}
}
bindingSource = new BindingSource() { DataSource = _criteriasBindingList };
DataGridView1.DataSource = bindingSource;
MessageBox.Show("OrderDetail In successfully updated");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "OrderDetail", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
public class OrderDetail
{
public string Invono { get; set; }
public DateTime InvoDate { get; set; }
public string Days { get; set; }
public string ProductName { get; set; }
public int UnitPrice { get; set; }
public int Quantity { get; set; }
}
VB.Net
Public Class Form1
Private OrderDetail As List(Of OrderDetail)
Private bindingSource As BindingSource = Nothing
Private _criteriasBindingList As New SortableBindingList(Of OrderDetail)()
Public Sub New()
InitializeComponent()
Me.CenterToScreen()
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 Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.LoadData()
End Sub
Private Sub LoadData()
OrderDetail = New List(Of OrderDetail) From {
New OrderDetail() With {
.Invono = "PI0001",
.InvoDate = Convert.ToDateTime("06-05-2024"),
.Days = Convert.ToDateTime("06-05-2024").ToString("dddd"),
.ProductName = "TEST 1000",
.UnitPrice = 15000,
.Quantity = 20
},
New OrderDetail() With {
.Invono = "PI0002",
.InvoDate = Convert.ToDateTime("07-05-2024"),
.Days = Convert.ToDateTime("07-05-2024").ToString("dddd"),
.ProductName = "TEST 2000",
.UnitPrice = 25000,
.Quantity = 20
},
New OrderDetail() With {
.Invono = "PI0003",
.InvoDate = Convert.ToDateTime("06-05-2024"),
.Days = Convert.ToDateTime("06-05-2024").ToString("dddd"),
.ProductName = "TEST 3000",
.UnitPrice = 17000,
.Quantity = 20
},
New OrderDetail() With {
.Invono = "PI0004",
.InvoDate = Convert.ToDateTime("07-05-2024"),
.Days = Convert.ToDateTime("07-05-2024").ToString("dddd"),
.ProductName = "TEST 4000",
.UnitPrice = 18000,
.Quantity = 20
},
New OrderDetail() With {
.Invono = "PI0005",
.InvoDate = Convert.ToDateTime("06-05-2024"),
.Days = Convert.ToDateTime("06-05-2024").ToString("dddd"),
.ProductName = "TEST 5000",
.UnitPrice = 19000,
.Quantity = 20
}
}
_criteriasBindingList = New SortableBindingList(Of OrderDetail)(OrderDetail)
bindingSource = New BindingSource With {.DataSource = _criteriasBindingList}
DataGridView1.DataSource = bindingSource
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
End Sub
Private Sub myFilter(idPeople As String, InvoDate As String, days As String)
LoadData()
Dim data As IEnumerable(Of OrderDetail) = _criteriasBindingList
If Not String.IsNullOrEmpty(idPeople) Then
data = data.Where(Function(c) c.ProductName.ToLower().StartsWith(idPeople)).ToList()
End If
If Not String.IsNullOrEmpty(InvoDate) Then
Dim dt As Date
Dim isValid As Boolean = DateTime.TryParseExact(InvoDate, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, dt)
If isValid Then
data = data.Where(Function(c) c.InvoDate.ToString("dd-MM-yyyy").Equals(InvoDate)).ToList()
End If
End If
If Not String.IsNullOrEmpty(days) Then
data = data.Where(Function(c) c.Days.ToLower().StartsWith(days)).ToList()
End If
_criteriasBindingList = New SortableBindingList(Of OrderDetail)(CType(data, IList(Of OrderDetail)))
bindingSource.DataSource = _criteriasBindingList
End Sub
Private Sub TXT_FILTER(sender As Object, e As KeyEventArgs) Handles MaskedTextBoxInvoDate.KeyUp, TXTProductName.KeyUp, Txtdays.KeyUp
Dim ProductName = TXTProductName.Text.Trim().ToLower()
Dim InvoDate = MaskedTextBoxInvoDate.Text.Trim().ToLower()
Dim days = Txtdays.Text.Trim().ToLower()
myFilter(ProductName, InvoDate, days)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
_criteriasBindingList = New SortableBindingList(Of OrderDetail)(CType(bindingSource.DataSource, IList(Of OrderDetail)))
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 OrderDetail = _criteriasBindingList(row2.Index)
' Checking InvoDate in MaskedTextBoxInvoDate.
If MaskedTextBoxInvoDate.Text = " - -" Then
_criteriasBindingList.Item(i).InvoDate = CDate(MaskedTextBox1.Text)
Else
If Not String.IsNullOrEmpty(MaskedTextBoxInvoDate.Text.Replace("-", "").Trim()) Then
_criteriasBindingList.Item(i).InvoDate = CDate(MaskedTextBox1.Text)
End If
End If
' Checking ProductName in textbox1.
If Not String.IsNullOrEmpty(TXTProductName.Text) Then
_criteriasBindingList.Item(i).ProductName = TXTProductName.Text
End If
End If
i = i + 1
Next row2
End If
bindingSource = New BindingSource With {.DataSource = _criteriasBindingList}
DataGridView1.DataSource = bindingSource
MessageBox.Show("OrderDetail In successfully updated")
Catch ex As Exception
MessageBox.Show(ex.Message, "OrderDetail", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End Sub
End Class
Public Class OrderDetail
Public Property Invono As String
Public Property InvoDate As DateTime
Public Property Days As String
Public Property ProductName As String
Public Property UnitPrice As Integer
Public Property Quantity As Integer
End Class
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
public class SortableBindingList<T> : BindingList<T> where T : class
{
private bool _isSorted;
private ListSortDirection _sortDirection = ListSortDirection.Ascending;
private PropertyDescriptor _sortProperty;
/// <summary>
/// Initializes a new instance of the <see cref="SortableBindingList{T}"/> class.
/// </summary>
public SortableBindingList()
{
}
/// <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 SortableBindingList(IList<T> list) : base(list)
{
}
/// <summary>
/// Gets a value indicating whether the list supports sorting.
/// </summary>
protected override bool SupportsSortingCore
{
get
{
return true;
}
}
/// <summary>
/// Gets a value indicating whether the list is sorted.
/// </summary>
protected override bool IsSortedCore
{
get
{
return _isSorted;
}
}
/// <summary>
/// Gets the direction the list is sorted.
/// </summary>
protected override ListSortDirection SortDirectionCore
{
get
{
return _sortDirection;
}
}
/// <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 override PropertyDescriptor SortPropertyCore
{
get
{
return _sortProperty;
}
}
/// <summary>
/// Removes any sort applied with ApplySortCore if sorting is implemented
/// </summary>
protected override void RemoveSortCore()
{
_sortDirection = ListSortDirection.Ascending;
_sortProperty = null;
_isSorted = false; // thanks Luca
}
/// <summary>
/// Sorts the items if overridden in a derived class
/// </summary>
/// <param name="prop"></param>
/// <param name="direction"></param>
protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
{
_sortProperty = prop;
_sortDirection = direction;
List<T> list = Items as List<T>;
if (list == null)
return;
list.Sort(Compare);
_isSorted = true;
// fire an event that the list has been changed.
OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
}
private int Compare(T lhs, T rhs)
{
var result = OnComparison(lhs, rhs);
// invert if descending
if (_sortDirection == ListSortDirection.Descending)
result = -result;
return result;
}
private int OnComparison(T lhs, T rhs)
{
object lhsValue = lhs == null ? null : _sortProperty.GetValue(lhs);
object rhsValue = rhs == null ? null : _sortProperty.GetValue(rhs);
if (lhsValue == null)
return rhsValue == null ? 0 : -1;// nulls are equal
if (rhsValue == null)
return 1;// first has value, second doesn't
if (lhsValue is IComparable)
return (IComparable)lhsValue.CompareTo(rhsValue);
if (lhsValue.Equals(rhsValue))
return 0;// both are the same
// not comparable, compare ToString
return lhsValue.ToString().CompareTo(rhsValue.ToString());
}
}
VB.NET
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
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
Screenshot