Home > OS >  Richtextbox to datagridview
Richtextbox to datagridview

Time:09-16

I have lines in a richtextbox with information with separators between them. I want to load it into a datagridview in with columns
ID | Name | Rank | Status

I need to split it by ";".

Richtextboxlines

My code does not use the separator.

Dim Separador As Char = ";"
Dim datagrid As New DataTable
Dim dr As DataRow

'==========================================
datagrid.Columns.Add("ID")
datagrid.Columns.Add("Name")
datagrid.Columns.Add("Rank")
datagrid.Columns.Add("Status")

dr = datagrid.NewRow()
'==========================================

Dim myList1 As New List(Of String)
myList1.AddRange(RichTextBox2.Lines)
DataGridView1.ColumnCount = 1

Dim row As String()
Dim counter As Integer = 0
Dim columnIndex As Integer = 0
'Initialize maximum rows needed
DataGridView1.Rows.Add(1000)
For index = 0 To RichTextBox2.Lines.Count - 1
    row = New String() {myList1(index)}
    'Fill per row and cell
    DataGridView1.Rows(counter).Cells(columnIndex).Value = row(0).ToString()
    counter  = 1
    If counter = 1000 Then
        columnIndex  = 1
        'Add new column
        Dim col As New DataGridViewTextBoxColumn
        ' DataGridView1.Rows.Add(col)
        '   DataGridView1.Columns.Add(col)
        counter = 0
        DataGridView1.DataSource = datagrid
    End If
Next

CodePudding user response:

You might get more utility by parsing each line of the data into a class; that data can then be stored in a List; and that List can be the DataSource for the DataGridView.

Once you get the hang of it, it's quite easy to manipulate the data with LINQ once it is in a List.

E.g., with RichTextBox1 and DataGridView1 on a form:

Public Class Form1

    Public data As New List(Of Datum)

    Public Class Datum
        Property ID As Integer
        Property Name As String
        Property Rank As String
        Property Status As String
    End Class

    Sub FillDGV()
        DataGridView1.DataSource = data

    End Sub

    Sub ExtractData()
        data.Clear()

        For Each line In RichTextBox1.Lines
            Dim parts = line.Split(";"c)
            If parts.Count = 4 Then
                data.Add(New Datum() With {
                         .ID = CInt(parts(0)),
                         .Name = parts(1),
                         .Rank = parts(2),
                         .Status = parts(3)})

            End If
        Next

    End Sub

    Sub FillRTB()
        For i = 1 To 10
            RichTextBox1.AppendText($"{i};{ChrW(64   i)};{10 - i};✓" & vbLf)
        Next

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        FillRTB()
        ExtractData()
        FillDGV()

    End Sub

End Class
  • Related