Link to home
Start Free TrialLog in
Avatar of Wilder1626
Wilder1626Flag for Canada

asked on

VB.Net Build string based on DataGridView values from a single column

Hi

I have this problem generating a string based on all the values from a DataGridView column.


Ex. If in my grid, i have:

User generated image
I would like to generate a string that will be puted into my txEquipmentCompatibilityString.Text as below:

('010','050','063','069')

Open in new window

The problem i have is that i only get ('010') with the below code:

'Build String
        Dim s As String

        For n = 0 To dgvLoadCommodities.RowCount - 1

            If String.IsNullOrEmpty(dgvLoadCommodities.Rows(n).Cells(0).Value) Then
            Else
                s = "'" + dgvLoadCommodities.Rows(n).Cells(0).Value.ToString.Replace("'", "''") + "'"
            End If
        Next

        txEquipmentCompatibilityString.Text = "" & "(" + " '" + dgvLoadCommodities.Rows(0).Cells(0).Value.ToString.Replace("'", "''") + "')"

Open in new window


How can i fix that.


Thanks again for your help.

Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

you have a couple of issues:
1. on line 8, you always overwrite the content of s, you never append to it
2. you don't use the value of s outside your loop
3. on line 12, you specifically display rows 0 content

give a try to :
'Build String         
Dim s As String = string.empty 
For n = 0 To dgvLoadCommodities.RowCount - 1             
   If not String.IsNullOrwhitespace(dgvLoadCommodities.Rows(n).Cells(0).Value) Then            
      if not string.isnullorwhitespace(s) then s &= ","
      s &= "'" + dgvLoadCommodities.Rows(n).Cells(0).Value.ToString.Replace("'", "''") + "'"             
   End If         
Next         
txEquipmentCompatibilityString.Text = "" & "(" + " '" + s.Replace("'", "''") + "')"

Open in new window

Avatar of Wilder1626

ASKER

Hi Éric
With this code, i have a problem. I'm getting double quotes and triple quotes in the string:
( '''010'',''014'',''015'',''038''')

Instead of
( '010','014','015','038')
ASKER CERTIFIED SOLUTION
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you so much. This is what i was looking for.