是否可以从单个数据源拥有图表控件的多个实例



有没有一种方法可以创建一个始终从同一数据源填充的图表控件,但我可以在应用程序中放置该控件的多个实例?

例如,我有一个图表控件,它显示了一周内所有用户作业的计数。我从数据库中提取数据(在计时器控件上)并更新图表。这对一个例子来说很好。

但是,是否可以将同一图表放在不同的表单(甚至两个其他表单)上,该表单是根据相同的数据自动更新的?而不是必须在每个图表的单独计时器上运行单独的查询?

我猜一个类可能是一条路,但我不确定如何正确设置它。

更新

很抱歉与我的帖子有任何混淆。我的例子是,我在表单上有一个从数据库填充的图表。如果用户愿意,我想让他们能够将该图表的"副本"添加到仪表板中。因此,我需要两个图表同时从相同的数据进行更新,而无需运行多个查询。希望这是有道理的。

控件只能是一个父级的子级。但是,如果克隆只应该是可见的,而不是交互式的,你可以使用一个小的肮脏的解决方法:

Public Class CloneChartControl
    Inherits System.Windows.Forms.DataVisualization.Charting.Chart
    'Add pictureboxes to this list that should show the data
    Public Clones As List(Of PictureBox)
    Private paintclones As Boolean = True
    Private oldbmp As Bitmap
    'Override the paint event
    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        MyBase.OnPaint(e)
        'Reasons not to paint the clones
        If paintclones = False Then Exit Sub
        If Clones Is Nothing Then Exit Sub
        Dim bmp As New Bitmap(Me.ClientRectangle.Width, Me.ClientRectangle.Height)
        'Disable the drawing of the clones while the chart's bitmap is drawn (recursiveness, will call OnPaint itself)
        paintclones = False
        Me.DrawToBitmap(bmp, Me.ClientRectangle)
        paintclones = True
        'Clean up the old image
        If oldbmp IsNot Nothing Then oldbmp.Dispose()
        oldbmp = bmp
        'Set the new image to all clone pictureboxes
        For Each p As PictureBox In Clones
            p.Image = bmp
        Next
    End Sub
End Class

其想法是将图表绘制为位图,并将位图设置为用作克隆的图片框的图像。每当重新绘制图表时,图片框也会更新。

不幸的是,图表似乎没有用.DrawToBitmap方法中作为参数给定的边界来绘制自己。我首先有一个类的草稿,它将为每个单独的picturebox创建一个新的位图,并带有picturebox的边界,但图表仍然只能以旧的大小绘制。因此,我稍微简化了代码。

最新更新