fill a listbox with data from the datagridview

JohnDW

Well-known member
Joined
Jun 13, 2012
Messages
60
Location
Antwerp, Belgium
Programming Experience
1-3
Hello,

I'm working on a code to fill a listbox with data from a datagridview and be able copy to clipboard.

The code I have:
VB.NET:
Dim endAt As Integer
        Dim StoreAnswer As String
        Dim i As Integer
       endAt = CInt(DataGridView1.RowCount - 1)
 Dim StoredAnswers(endAt) As String
        For i = 0 To endAt            
            StoreAnswer = CStr(DataGridView1.Rows(i).Cells(2).Value) 
            i = i + 1
            ListBox1.Items.Add(StoreAnswer & ";")
        Next i

This code works, but it gives me every storeanswer on another line.
I'm looking for a way to write storeanswer on one line , fill it with 50 storeanswer seperated by a semicolon,
and go to the next line, fill it again with 50 untel endAt.

I was looking on the net, but couldn't find an way to do it.

Then I want to Copy it to the clipboard .
Therefore I set SelectionMode.MultiExtended
I found the following code on the net
VB.NET:
[FONT=Consolas][SIZE=2] Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles ListBox1.KeyDown
        If e.Control AndAlso e.KeyCode = Keys.C Then
            Dim copy_buffer As New System.Text.StringBuilder
            For Each item As Object In ListBox1.SelectedItems
                copy_buffer.AppendLine(item.ToString)
            Next
            If copy_buffer.Length > 0 Then
                Clipboard.SetText(copy_buffer.ToString)
                MessageBox.Show("Copied Items to Clipboard")
            End If
        End If
    End Sub
[/SIZE][/FONT]

But this code don't work.

Some hints?

John
 
Last edited:
You don't have to find a way to do it on the web. Think about how you might do it. As I say many times, programming doesn't exist in a vacuum. How would you do it in "real life"? You go through your list and add the values to some temporary holding area until you had 50 of them and then you'd add that 50 to the final list as a group, right? Well, lo and behold, that's exactly how you do it in code too.

Where could you store some Strings temporarily? In a List(of String) maybe? So just loop through grid and add your values to a List(Of String). When that List gets to 50 items or you get to the end of the grid, join all the items together into a single String, which you can do using String.Join, and add that to the ListBox and then clear the List. On you go.
 
That's all I ask. If you can't get it to work then by all means show us what you've done and I'll be glad to help you fix it but do what you can for yourself first. The best way to learn is to do, and failure is all part of the learning process.
 
Back
Top