简体   繁体   中英

How to link a string to a datagridview in VB.net

I have a dataset that contains multiple values. With Regex, I could take specific rows from the datatable BLABLA. I stored them in the string answer . Now I want to display answer in a datagridview. This is how one line in answer looks like:

A24.06.2018 13:20:34BLABLA 11/1110 A 2S3/11 1234C:\\Users\\someone\\Desktop\\file

The datagridview already contains the needed columns. The lines need to fit in the columns that means they need to be split according to the columns.I never worked with DataSource, so I don't know how it should look like.

I already tried to display answer in a MessageBox to see if I have the values that I searched for and I do. But when I try ErrorsDGV.DataSource = answer nothing happens.

Dim answer As String = ""
Dim myregex As Regex = New Regex("S[0-6]")

Dim SearchRows() As DataRow = datasetB.Tables("BLABLA").Select().
Where(Function(r) myregex.IsMatch(r.Item("Data"))).ToArray()

For k As Integer = 0 To SearchRows.Length - 1
    If answer = "" Then
        answer = String.Join("", SearchRows(k).ItemArray())
    Else
        answer = answer & vbNewLine & String.Join("", SearchRows(k).ItemArray())

    End If
Next

ErrorsDgV.DataSource = answer

What am I doing wrong? How does a DataSource have to look like to be used as a source for a DataGridView? Thanks in advance.

You don't need this code:

For k As Integer = 0 To SearchRows.Length - 1
    If answer = "" Then
        answer = String.Join("", SearchRows(k).ItemArray())
    Else
        answer = answer & vbNewLine & String.Join("", SearchRows(k).ItemArray())

    End If
Next

You already have the rows you want to display in here:

Dim SearchRows() As DataRow = datasetB.Tables("BLABLA").Select().
Where(Function(r) myregex.IsMatch(r.Item("Data"))).ToArray()

So set the grid datasource to this:

ErrorsDgV.DataSource = SearchRows

I could solve the question by using CopyToDataTable and by changing SearchRows to a DataTable instead of a DataRow as you can see below:

Dim SearchRows As DataTable = datasetB.Tables("BLABLA").Select().
    Where(Function(r) myregex.IsMatch(r.Item("Data"))).ToArray().CopyToDataTable

Then I used SearchRows as my DataSource

ErrorsDgV.DataSource = SearchRows

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM