将datagridview保存为CSV而不更改焦点

时间:2015-04-06 02:27:38

标签: vb.net csv datagridview

我使用以下代码将DataGridView表保存到文本文件中:



Dim rows = From row As DataGridViewRow In DataGridView1.Rows.Cast(Of DataGridViewRow)() _
                   Where Not row.IsNewRow _
                   Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
        Using sw As New IO.StreamWriter("Z:\\SchData.txt")
            For Each r In rows
                sw.WriteLine(String.Join(";", r))
            Next
        End Using




以下更新表:



 While 1 = 1
            Try
                DataGridView1.Rows.Clear()
                Using stream As System.IO.FileStream = System.IO.File.OpenRead("Z:\\SchData.txt")
                    Using reader As New System.IO.StreamReader(stream)

                        Dim line As String = reader.ReadLine()

                        While (line IsNot Nothing)
                            Dim columns = line.Split(";")
                            line = reader.ReadLine()
                            Dim index = Me.DataGridView1.Rows.Add()
                            Me.DataGridView1.Rows(index).SetValues(columns)
                        End While

                    End Using
                End Using
                Button107.Enabled = True
                Button88.Enabled = True
                updatingSch = False
                Return
            Catch ex As Exception
                Threading.Thread.Sleep(50)
            End Try
        End While




当我更改表中的值时,将调用这两个函数。问题是,不是转到下一个单元格(当我选中,输入或单击另一个单元格)时,它会将焦点设置为正确的单元格,但随后会快速切换到左上角的单元格(第0行,列0)。如何阻止它改变焦点?

1 个答案:

答案 0 :(得分:0)

这是编辑后如何保持在同一行。

Private Sub dgv_CellEndEdit(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv.CellEndEdit
  Dim index As Integer = dgv.FirstDisplayedScrollingRowIndex
    'do your file work then reset the row index 
  dgv.FirstDisplayedScrollingRowIndex = index
End Sub