比较数据从DataGridView控件到不断更新的数据表(循环问题)



我有一个DataTable,它通过计时器不断更新数据库中的新数据。该数据最终被重新格式化并显示在DataGridView控件中。

为了防止DataGridView从重新数据绑定中完全刷新(因此,清除选择,重置滚动条,默认排序设置,并使gridview在重新更新时闪烁),我只是从DataTable中不再存在的数据网格中删除旧行,并向自上次更新以来出现在DataTable中的数据网格添加新行。

为简单起见,我们将DataGridView称为表,将DataTable称为

我正在寻找一种方法去通过两个表(左和右),并删除旧的行不再在右,并从左删除它们。并在RIGHT中查找新项并将其添加到LEFT中。每个表都有一个名为"RecID"的列,其中包含每个条目的唯一id,可用于比较。

现在,我的问题是…有没有一种方法可以在一个循环中完成这些?我在寻找什么,在伪代码:

<loop through everything>
    if RecID does not exist in LEFT but exists in RIGHT
        add new item to LEFT
    if RecID does exist in LEFT but does not exist in RIGHT
        delete item from LEFT
    if RecID does exist in LEFT and also exists in RIGHT, check each cell in row and update LEFT.. i can handle this part
<end loop>

现在每个进程有两个嵌套循环,一个用于添加条目,一个用于删除条目。这需要更多的处理,如果我能一次完成的话。但我想不出一个一次性解决的方法。这是我的代码。

'Add new items (alert)
        For Each dr As DataRow In alertTableNew.Rows()
            Dim found As Integer = -1
            For Each gr As DataGridViewRow In DataGridView1.Rows()
                If dr.Item("RecID") = gr.Cells("RecID").Value Then
                    found = dr.Item("RecID")
                    gr.Cells("status").Value = dr.Item("status") 'status may change, update it here
                End If
                If found = -1 Then
                    DataGridView1.Rows.Add( _
                        dr.Item("line"), _
                        dr.Item("acct"), _
                        dr.Item("alarmdescription"), _
                        dr.Item("status"), _
                        dr.Item("name"), _
                        dr.Item("RecID"))
                End If
            Next
        Next
        'Remove expired items (alert)
        For Each gr As DataGridViewRow In DataGridView1.Rows()
            Dim found As Integer = -1
            For Each dr As DataRow In alertTableNew.Rows()
                If Not gr Is Nothing And gr.Cells("RecID").Value = dr.Item("RecID") Then
                    found = dr.Item("RecID")
                    gr.Cells("status").Value = dr.Item("status") 'status may change, update it here
                End If
                If found = -1 Then
                    DataGridView1.Rows().Remove(gr)
                End If
            Next
        Next

我的代码似乎非常低效。感谢任何帮助。谢谢!

我正在放置一个简单的解决方案,其中我比较了两个datagridviews单元格的值,并在第三个datagridview中显示这些值:

        for (int i = 0; i < dtView1.Rows.Count; i++)
        {
            for (int j = 1; j < dtView1.Columns.Count; j++)
            { 
               dtViewResult.Rows[i][j] = (dtView1.Rows[i][j].ToString()) + (dtView2.Rows[i][j].ToString()); 
            }
         }

c#,我认为无论是桌面应用程序还是Web应用程序都支持你所说的"开箱即用"的特性。它被称为数据绑定。在网上找一个例子,DataGridView.DataSourceBindingSourceDataBind()

如前所述,数据库绑定是解决方案的一部分,但是还有更多的东西可以得到您正在寻找的。DataTable有一个Merge方法,它将合并现有表和对该表(或具有类似模式的另一个表)的更新,以补偿添加、更改和删除。查看这篇MSDN文章,了解该方法的描述。

http://msdn.microsoft.com/en-us/library/9dkss51z.aspx

最新更新