简体   繁体   English

如何将队列绑定到C#/ Winforms中的DataGridView?

[英]How can I bind a Queue to a DataGridView in C#/Winforms?

I have a standard C# queue, declared like this: 我有一个标准的C#队列,声明如下:

private Queue<DeployJob> _solutionQueue = new Queue<DeployJob>();

Now I want to bind this queue to an DataGridView, which is placed inside a winform. 现在我想将这个队列绑定到一个DataGridView,它放在一个winform中。 With "bind" i mean that everytime i dequeue or enqueue an item from the queue the DataGridView gets updated (so that it always represents the state of the queue). 使用“绑定”,我的意思是每当我从队列中dequeueenqueue一个项目时, DataGridView就会被更新(这样它总是代表队列的状态)。

I have tried to bind it this way: 我试图用这种方式绑定它:

jobGridView.DataSource = _solutionQueue;

But it doesnt work, even if I use the update or refresh methods. 但它不起作用,即使我使用updaterefresh方法。 If you need more code, please feel free to ask :) 如果您需要更多代码,请随时问:)

According to MSDN , the DataGridView.DataSource must implement one of the following interfaces: 根据MSDNDataGridView.DataSource必须实现以下接口之一:

  • IList
  • IListSource
  • IBindingList
  • IBindingListView

The Queue<T> class implements parent interfaces of IList , including IEnumerable and ICollection , but not IList itself. Queue<T>类实现IList父接口,包括IEnumerableICollection ,但不是IList本身。

One suggestion is to use LINQ to create a List<DeployJob> from the queue and bind like so: 一个建议是使用LINQ从队列创建List<DeployJob>并像这样绑定:

using System.Linq;    

//code

jobGridView.DataSource = _solutionQueue.ToList();

You would want to make sure and handle any events that update/modify the queue, and re-bind the DataGridView to a newly created List 您可能希望确保并处理更新/修改队列的任何事件,并将DataGridView重新绑定到新创建的List

I created a generic queue type that makes a queue observable and a derived type that makes this new queue behave like a list and a binding list. 我创建了一个通用队列类型,它使队列可观察,并且派生类型使这个新队列的行为类似于列表和绑定列表。 This works for read only features of a datagridview. 这适用于datagridview的只读功能。 You would need to extend further if you need additional functionality. 如果您需要其他功能,则需要进一步扩展。

Observable concurrent queue: 可观察的并发队列:

Imports System.Collections.Concurrent
Imports System.Collections.Specialized

Public Class ObservableConcurrentQueue(Of T)
    Inherits ConcurrentQueue(Of T)
    Implements INotifyCollectionChanged

    Public Event CollectionChanged(sender As Object, e As NotifyCollectionChangedEventArgs) Implements INotifyCollectionChanged.CollectionChanged
    Private Sub OnCollectionChanged(ByVal args As NotifyCollectionChangedEventArgs)
        RaiseEvent CollectionChanged(Me, args)
    End Sub

    Public Shadows Sub Enqueue(ByVal item As T)
        MyBase.Enqueue(item)
        OnCollectionChanged(New NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item))
    End Sub

    Public Shadows Function TryDequeue(ByRef result As T) As Boolean
        If Not MyBase.TryDequeue(result) Then
            Return False
        End If

        OnCollectionChanged(New NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, result))

        Return True
    End Function

End Class

Wrap it further to behave like a list and abindinglist: 进一步包装,表现得像列表和abindinglist:

Imports System.Linq
Imports System.ComponentModel
Imports System.Collections.Specialized
Imports System.Linq.Expressions

Public Class ObservableConcurrentQueueList(Of T)
    Inherits ObservableConcurrentQueue(Of T)
    Implements IList(Of T), IBindingList

    Public Sub Clear()
        Dim item As T
        While (Not IsEmpty())
            MyBase.TryDequeue(item)
        End While
    End Sub

#Region "IList Implementation"

    Public Sub Add1(item As T) Implements ICollection(Of T).Add
        MyBase.Enqueue(item)
    End Sub

    Protected Sub Clear1() Implements ICollection(Of T).Clear
        Clear()
    End Sub

    Protected Function Contains1(item As T) As Boolean Implements ICollection(Of T).Contains
        Return MyBase.Contains(item)
    End Function

    Protected Sub CopyTo1(array() As T, arrayIndex As Integer) Implements ICollection(Of T).CopyTo
        MyBase.CopyTo(array, arrayIndex)
    End Sub

    Protected ReadOnly Property Count1 As Integer Implements ICollection(Of T).Count
        Get
            Return MyBase.Count
        End Get
    End Property

    Protected ReadOnly Property IsReadOnly1 As Boolean Implements ICollection(Of T).IsReadOnly
        Get
            Return True
        End Get
    End Property

    Protected Function Remove1(item As T) As Boolean Implements ICollection(Of T).Remove
        Throw New NotImplementedException
    End Function

    Protected Function IndexOf1(item As T) As Integer Implements IList(Of T).IndexOf
        Return Me.ToList.IndexOf(item)
    End Function

    Protected Sub Insert1(index As Integer, item As T) Implements IList(Of T).Insert
        Throw New NotImplementedException
    End Sub

    Protected Property Item1(index As Integer) As T Implements IList(Of T).Item
        Get
            Return Me.ToList.Item(index)
        End Get
        Set(value As T)
            Throw New NotImplementedException
        End Set
    End Property

    Protected Sub RemoveAt1(index As Integer) Implements IList(Of T).RemoveAt
        Throw New NotImplementedException
    End Sub

#End Region

#Region "IBindList Implementation"

    Protected Function Add2(value As Object) As Integer Implements IList.Add
        'Throw New NotImplementedException
        MyBase.Enqueue(value)
        Return Nothing
    End Function

    Protected Sub Clear2() Implements IList.Clear
        Clear()
    End Sub

    Protected Function Contains2(value As Object) As Boolean Implements IList.Contains
        Return MyBase.Contains(value)
    End Function

    Protected Function IndexOf2(value As Object) As Integer Implements IList.IndexOf
        Return Me.ToList.IndexOf(value)
    End Function

    Protected Sub Insert2(index As Integer, value As Object) Implements IList.Insert
        Throw New NotImplementedException
    End Sub

    Protected ReadOnly Property IsFixedSize2 As Boolean Implements IList.IsFixedSize
        Get
            Return False
        End Get
    End Property

    Protected ReadOnly Property IsReadOnly2 As Boolean Implements IList.IsReadOnly
        Get
            Return True
        End Get
    End Property

    Protected Overloads Property Item2(index As Integer) As Object Implements IList.Item
        Get
            Return Me.ToList.Item(index)
        End Get
        Set(value As Object)
            Throw New NotImplementedException
        End Set
    End Property

    Protected Sub Remove2(value As Object) Implements IList.Remove
        Throw New NotImplementedException
    End Sub

    Protected Sub RemoveAt2(index As Integer) Implements IList.RemoveAt
        Throw New NotImplementedException
    End Sub

    Protected Sub AddIndex2([property] As PropertyDescriptor) Implements IBindingList.AddIndex

    End Sub

    Protected Function AddNew2() As Object Implements IBindingList.AddNew
        Throw New NotImplementedException
    End Function

    Protected ReadOnly Property AllowEdit2 As Boolean Implements IBindingList.AllowEdit
        Get
            Return False
        End Get
    End Property

    Protected ReadOnly Property AllowNew2 As Boolean Implements IBindingList.AllowNew
        Get
            Return False
        End Get
    End Property

    Protected ReadOnly Property AllowRemove2 As Boolean Implements IBindingList.AllowRemove
        Get
            Return False
        End Get
    End Property

    Protected Sub ApplySort2([property] As PropertyDescriptor, direction As ListSortDirection) Implements IBindingList.ApplySort
        Throw New NotImplementedException
    End Sub

    Protected Function Find2([property] As PropertyDescriptor, key As Object) As Integer Implements IBindingList.Find
        Throw New NotImplementedException
        Return Nothing
    End Function

    Protected ReadOnly Property IsSorted2 As Boolean Implements IBindingList.IsSorted
        Get
            Return False
        End Get
    End Property

    Protected Event ListChanged2(sender As Object, e As ListChangedEventArgs) Implements IBindingList.ListChanged

    Protected Sub RemoveIndex2([property] As PropertyDescriptor) Implements IBindingList.RemoveIndex
        Throw New NotImplementedException
    End Sub

    Protected Sub RemoveSort2() Implements IBindingList.RemoveSort
        'Throw New NotImplementedException
    End Sub

    Protected ReadOnly Property SortDirection2 As ListSortDirection Implements IBindingList.SortDirection
        Get
            'Throw New NotImplementedException
        End Get
    End Property

    Protected ReadOnly Property SortProperty2 As PropertyDescriptor Implements IBindingList.SortProperty
        Get
            Throw New NotImplementedException
            Return Nothing
        End Get
    End Property

    Protected ReadOnly Property SupportsChangeNotification2 As Boolean Implements IBindingList.SupportsChangeNotification
        Get
            Return True
        End Get
    End Property

    Protected ReadOnly Property SupportsSearching2 As Boolean Implements IBindingList.SupportsSearching
        Get
            Return False
        End Get
    End Property

    Protected ReadOnly Property SupportsSorting2 As Boolean Implements IBindingList.SupportsSorting
        Get
            Return False
        End Get
    End Property

#End Region

End Class

Use it in a form: 在表格中使用它:

Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    DataGridView1.AutoGenerateColumns = True
    Me.DataGridView1.DataSource = MyObservableQueueList

    AddHandler MyObservableQueueList.CollectionChanged, AddressOf UpdateGrid
End Sub

Private Sub UpdateGrid(sender As Object, e As System.Collections.Specialized.NotifyCollectionChangedEventArgs)
    Me.MyObservableQueueList.DataSource = Nothing
    Me.MyObservableQueueList.DataSource = _AlarmHistory
End Sub

Protected Overrides Sub Dispose(ByVal disposing As Boolean)
    Try
        RemoveHandler MyObservableQueueList.CollectionChanged, AddressOf UpdateGrid
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
        End If
    Finally
        MyBase.Dispose(disposing)
    End Try
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不使用saveFileDialog C#Winforms提示用户的情况下将dataGridView轻松保存到.XLS或.CSV? - How can I easily save dataGridView to .XLS or or .CSV without prompting user with saveFileDialog C# Winforms? C#Winforms - 如何在datagridview中托管用户控件(带子代)来响应鼠标事件? - C# Winforms - How can I have user controls (with children) hosted in a datagridview respond to mouse events? C#WinForms BindingList和DataGridView-禁止进行编辑会阻止创建新行? 我该如何解决? - C# WinForms BindingList & DataGridView - disallowing EDIT prevents creation of a NEW row? How can I address this? 使用我在DataGridView上绑定的类中的属性(ComponentModel?)设置列宽(C#,WinForms) - Set column width using attribute (ComponentModel?) in class which I bind on DataGridView (C#, WinForms) C#WinForms:如何强制DataGridView绑定其来自数据源的数据 - C# WinForms: How to enforce the DataGridView to bind its data from the data source 我可以将多维数据绑定到C#和.NET中的DataGridView吗? - Can I bind multidimensional data to a DataGridView in C# and .NET? 如何使用C#将XML Web响应绑定到Windows窗体中的dataGridView中? - How can I bind a XML web response into a dataGridView in a Windows Forms using C#? 如何在C#中打印DataGridView? - How can i print DataGridView in C# ? 如何在C#中使用2个按钮排队和更新dataGridView? - How to queue and update a dataGridView with 2 buttons in C#? WinForms C#-显示DataGridView - WinForms C# - Display DataGridView
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM