How to Paste data from DataTable to DataGridView with linq (without using a '.DataSource')

Mansour_Dalir 2,036 Reputation points
2023-06-20T06:01:02.94+00:00

hi

In order to have the data on the DataGridView (without using a '.DataSource', because with this I don't have the problem of skipping rows when sorting), I want to use Linq with high speed. (All the code changes are due to the row skipping issue) Thank you very much My efforts so far :

         Dim dtMain As New DataTable()
        dtMain.Columns.Add("id")
        dtMain.Columns.Add("c1")
        dtMain.Columns.Add("c2")
        dgv.Columns.Add("id", "id")
        dgv.Columns.Add("c1", "c1")
        dgv.Columns.Add("c2", "c2")
        For r = 0 To 20000
            dtMain.Rows.Add(r, "a" & r, "b" & r)
        Next
        Dim gRow(dtMain.Rows.Count - 1) As DataGridViewRow
        For a = 0 To dtMain.Rows.Count - 1
            gRow(a) = dgv.Rows(0).Clone
            gRow(a).Cells(0).Value = dtMain.Rows(a).Item("id")
            gRow(a).Cells(1).Value = dtMain.Rows(a).Item("c1")
            gRow(a).Cells(2).Value = dtMain.Rows(a).Item("c2")
        Next
        dgv.Rows.AddRange(gRow)

There is a method that can delete the '.DataSource', but the data remains in the 'DataGridView' ?dgv.DataSource=Nothing But the data remains ! )

Developer technologies | VB
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2023-06-20T06:24:50.7366667+00:00

    Hi @Mansour_Dalir ,

    You can refer to the following code.

            Dim dtMain As New DataTable()
            dtMain.Columns.Add("id")
            dtMain.Columns.Add("c1")
            dtMain.Columns.Add("c2")
            dgv.Columns.Add("id", "id")
            dgv.Columns.Add("c1", "c1")
            dgv.Columns.Add("c2", "c2")
            For r = 0 To 20000
                dtMain.Rows.Add(r, "a" & r, "b" & r)
            Next
            Dim query = From row As DataRow In dtMain.Rows
                        Select New With
                {
                    .Column1 = row("id"),
                    .Column2 = row("c1"),
                    .Column3 = row("c2")
                }
            For Each item In query
                dgv.Rows.Add(item.Column1, item.Column2, item.Column3)
            Next
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.