Avatar of Wilder1626
Wilder1626
Flag 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:


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.

Visual Basic.NET

Avatar of undefined
Last Comment
Wilder1626

8/22/2022 - Mon
Éric Moreau

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

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
Éric Moreau

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Wilder1626

ASKER
Thank you so much. This is what i was looking for.
Your help has saved me hundreds of hours of internet surfing.
fblack61