Get Rid of Trailing Comma in a String

 Hi,

I've got a CheckListBox in an email form, whose selected items will be added as a comma delimited list to my message variable (msg). I've managed to create the list and add it to the message, but I want to get rid of the last comma. Most of the examples that I found online are either not in the appropriate context, or they just don't work. I've also played around with the Mid function without any luck.

Here's my code:

--------------------- form.aspx ---------------------

<asp:CheckBoxList ID="cblValues" runat="server">
        <asp:ListItem>Item 1</asp:ListItem>
        <asp:ListItem>Item 2</asp:ListItem>
        <asp:ListItem>Item 3</asp:ListItem>
</asp:CheckBoxList>

<asp:Literal ID="ltlValues" runat="server" EnableViewState="False"  Visible="False"></asp:Literal>

 

--------------------- form.aspx.vb ---------------------

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

        'Declare the SMTP Client
        Dim client As New SmtpClient()
       
        'Declare a variable for the message body
        Dim msg As String
        msg = "Field 1: " & txtField1.Text & vbCrLf
        msg += "Field 2: " & txtField2.Text & vbCrLf
       
        'Store the CheckBoxList selected items in a Literal and add them to the message
        For Each item As ListItem In cblValues.Items
            If item.Selected Then
                ltlValues.Text += item.Text & ", "
            End If
        Next
        msg += "Field 3: " & ltlValues.Text
               
        'Create the message
        Dim mm As New MailMessage
        mm.From = New MailAddress("noreply@somedomain.com")
        mm.To.Add("myemail@somedomain.com")
        mm.Subject = "Some Subject"
        mm.Body = msg
        mm.IsBodyHtml = False

        'Send the message
        client.Send(mm)
        Response.Redirect("thanks.aspx")
       
    End Sub
 

When the form is submitted, the message output for Field 3 is this (if all items are selected): Item 1, Item 2, Item 3,

I would like to get rid of the comma after the last item in the list. Any help with this, in VB or C#, would be greatly appreciated. Thanks in advance. 

0
cmd_17
11/21/2007 6:40:20 PM
asp.net.getting-started 91979 articles. 3 followers. Follow

11 Replies
504 Views

Similar Articles

[PageSpeed] 36

Check out this Tip from ASPNet101.com:
http://www.aspnet101.com/aspnet101/tips.aspx?id=170


David Wier
MCP/ASPInsider
ASPNet101.com - where to look first!
Please Vote for ASPNet101 - 'Best Community Resource'!
Control Grouper - easily control properties for multiple controls with one control!
Calendar Express - The Best HTML Calendar Generator on the web!
(Please 'Mark as Answer' when it applies)
0
augustwind
11/21/2007 6:58:02 PM

Get the index of the last comma in your string

then remove that character from your string

You can use string.LastIndexOf(",")  function of the string.

For detail you can google 


Kamran Shahid
Sr. Software Engineer
(MCP,MCAD.net,MCSD.net,MCTS,MCPD.net[web])
Netprosys Inc.
www.netprosys.com

Remember to click "Mark as Answer" on the post that helps U
0
kamii47
11/21/2007 7:04:29 PM

 Instead of :

 

For Each item As ListItem In cblValues.Items
  If item.Selected Then
    ltlValues.Text += item.Text & ", "
  End If
Next

 

you could just do:

 

For Each item As ListItem In cblValues.Items
  If item.Selected Then
    ltlValues.Text += ltlValues.Text.Equals(string.Empty) ? item.Text : ", " & item.Text 
  End If
Next
 
0
Klaus
11/21/2007 7:18:10 PM

Thanks for the link, augustwind. I just used the String.Substring method instead of writing a separate function, and it worked perfectly. Here's what I did:

For Each item As ListItem In cblValues.Items
     If item.Selected Then
         ltlValues.Text += item.Text & ", "
     End If
Next

Dim strList As String = ltlValues.Text
strList = strList.Substring(0, strList.Length - 2)
msg += "Values: " & strList

 

Thanks again for your help. 

0
cmd_17
11/21/2007 9:22:44 PM

kamii47:

Get the index of the last comma in your string

then remove that character from your string

You can use string.LastIndexOf(",")  function of the string.

For detail you can google 

 

Thanks for the reply. Although I solved the problem another way, I'll make a note of your suggestion in case I need it for something in the future. 

0
cmd_17
11/21/2007 9:26:38 PM

cmd_17:

For Each item As ListItem In cblValues.Items
     If item.Selected Then
         ltlValues.Text += item.Text & ", "
     End If
Next

Dim strList As String = ltlValues.Text
strList = strList.Substring(0, strList.Length - 2)
msg += "Values: " & strList



You could do it in a simpler way, Use TrimEnd method

        string abc = "Item1, ITem2, Item3,";
        Response.Write(abc.TrimEnd(','));

 Thanks

-Mark post(s) as "Answer" that helped you


Mark post(s) as "Answer" that helped you

Electronic Screw
Website||Blog||Dub@i.net
0
e_screw
11/21/2007 9:30:30 PM

Klaus Byskov Pedersen:
ltlValues.Text += ltlValues.Text.Equals(string.Empty) ? item.Text : ", " & item.Text

Thanks for the reply. Unfortunately, the code gave me a "character is not valid" error for the ? and a syntax error for ", ".

0
cmd_17
11/21/2007 9:37:32 PM

e_screw:

You could do it in a simpler way, Use TrimEnd method

        string abc = "Item1, ITem2, Item3,";
        Response.Write(abc.TrimEnd(','));

 Thanks

 

Thanks for the suggestion. When I do this...

Dim strList As String = "Item 1, Item 2, Item 3,"
Response.Write(strList.TrimEnd(","))

...it works, but it doesn't work when I do this...

Dim strList As String = ltlValues.Text
Response.Write(strList.TrimEnd(","))

What am I doing wrong?

0
cmd_17
11/21/2007 10:00:32 PM

this would do the work (in c# though)

        String s = String.Empty;
        char[] charsToTrim = { ',' };
        s = "item1, item2, item3,";
        Response.Write(s.TrimEnd(charsToTrim));

 

bear in mind that if the last character is space then this will do no good

for example char s ="item1, item2 ,item3 " -->this will not work

to make it works just modified this

char[] charsToTrim = { ',',' ' };

0
deddy_one
11/21/2007 11:55:03 PM

cmd_17:

What am I doing wrong?

You got a space after the comma separator. In such case, you need to use char params as told deddy_one and pass that params to the TrimEnd method

char[] charsToTrim = { ',',' ' };

Thanks

-Mark post(s) as "Answer" that helped you

 


Mark post(s) as "Answer" that helped you

Electronic Screw
Website||Blog||Dub@i.net
0
e_screw
11/22/2007 7:42:16 AM

 It worked. Thanks for your help.

0
cmd_17
11/22/2007 9:27:02 PM
Reply:

Similar Artilces:

get rid of that ridiculous getting started bookmark
Name: DOCTOR Product: Firefox Summary: get rid of that ridiculous getting started bookmark Comments: Browser Details: Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_4_11; en) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.2 Safari/525.22 From URL: http://hendrix.mozilla.org/ Note to readers: Hendrix gives no expectation of a response to this feedback but if you wish to provide one you must BCC (not CC) the sender for them to see it. ...

POST GET GET GET GET... WTH?
Hi, I'm at a loss to explain this... I have an ASPX page that I can't always navigate to. When I developed the app (it's Starter Kit Portal-based), I did it on my LAN and have had no trouble accessing the page. However, upon deployment, I see the following behavior: 1. POST request goes out looking for MyForm.aspx 2. GET request for MyForm.aspx 3. GET request for MyForm.aspx 4. ... X. GET request Sometimes, the page finally loads. Other times, it just ends up blank. Many times, it doesn't load at ALL the first POST - I just get a "The pa...

Get rid of SM email or I get rid of browser!
I use Windows 7 and am FED UP with SM 2.0's demanding that I use its email client! I want the BROWSER ONLY. I've been using Pegasus Mail as my client since 1994 and wont stop. Yet something wont allow me to make that my default email client in SM, it opens SM's mail client for any email link I click on and wont allow it to be changed. I either get this to stop or I gotta find another browser, this is BULL! -- Jane Galt "There is no difference between communism and socialism, except in the means of achieving the same ultimate end: communism proposes t...

How do I get rid of this mozL10n.get()?
So I have a few strings that contains arguments that also needs to be translated https://github.com/mozilla-b2g/gaia/blob/42e93d96ea245c778885b1889b3da589f5342fb1/apps/keyboard/locales/keyboard.en-US.properties#L77 And at the time of writing the code I ended up using mozL10n.get(). https://github.com/mozilla-b2g/gaia/blob/42e93d96ea245c778885b1889b3da589f5342fb1/apps/keyboard/js/settings/layout_item_view.js#L263-L265 Do we already have support on this? The answer is probably obvious if there is already one. The status itself is one <span> element which I prefer not to break...

trying to get started and i am getting this error
when i go to http://www.porkchopsplayground.com, i get: DotNetNuke Upgrade Error The Assembly Version ( [ASSEMBLYVERSION] ) does not match the Database Version ( [DATABASEVERSION] ) ERROR: Could not connect to database. Could not find file 'd:\hosting\nmoran26\Providers\DataProviders\AccessDataProvider\DotNetNuke.mdb'. Any suggestions will be appreciated. Thanks, Nicole Do you have a username and password set on your database? Make sure you follow the steps mentionned in the Readme.txt located in the documentation folder. In any case make sure your credentials for yo...

How do I get get rid of 2nd login
I work at a company that is on a Novell network. We all run Novell client for Windows V. 4.9(2 I think). What I want to do it to get rid of the second log in screen. There is the original Novell Client login, then it prompts me for my workstation username and password. There are other computers that do not ask for the workstation info, they just create an account based on the novell info. This is good if you want to map another network share in a workgroup or something. Does anybody know how to do this? On another note, this computers are most all shared, so simply clicking t...

how to get start with .NET
the net help people installed  to my desktop 1-microsoft visual studio .NET enterprise developer 2003 2-microsoft .NET framework 1.1 what else do i need ...???  and how can i try with some simple code in VS.Net and run it to see wat happen...????? please help If you want to develope web applications, then you'll also need IIS on your PC.  That'll require XP-Professional or Windows 2000/2003, but XP-Home edition won't allow IIS installation. As for how to get started, you can search the web for some tutorials or buy a good book on VS.  The topic is way too vast to...

Getting Start With .net
hi i'm intersted to learn asp.net (vb or delphi) . i programming with delphi6 but i'd like to tp know something about programming in internet specially with .net . i hear about microsoft.net with delphi 7 that i can programming with delphi in .net .... is it right ? what 's our opinian about it ? and better to learn Vb.Net or continu with delphi(or delphi.net) thanks. Ali Darabian I think there is some support for Delphi in .Net. However, you will find much more support from the user community if you choose a more popular language such as VB.Net or C#. Since your al...

Getting rid of the last comma in a comma delimited list on a datalist.
I may be going about this the wrong way but I have a list of authors that I'm trying to display in a browser as a comma delimited list. e.g. Author 1, Author 2, Author 3, etc... I created a template in a datalist containing a hyperlink (to the author page) and a comma (,). I'd like to get rid of the last comma. Does anyone have any idea's. Am I approaching this in the wrong way? Any help would be appreciated. Thanks in advance M Have you looked into using the SeperatorTemplate?  It is the section of html that will be emitted between each of your ItemTemplates. ...

getting started in VS2005 C# which book should I get
Hello, I am getting started with VS2005, I have use VS2003 but not very much -(I did 4 small applications in it),  I am wondering which book you would recommend to learn the new features of VS2005, while learning more of C# programing in general There some links to good books in this thread i posted : http://forums.asp.net/thread/1489422.aspx Also these two make good reference material  Professional Visual Studio 2005 (Programmer to Programmer)   Microsoft Visual Studio 2005 Unleashed  So far I recommend Wrox's C# 2005  Read the beginning chap...

Getting error in Net::SFTP with get function
------=_Part_7028_3315294.1193837808284 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline Hi All, I have the following code as part of my program; print "---=========> $file, $localFile\n"; $sftp -> get( $file, $localFile ) || warn("errrrr0rrrrr _---> $!".$sftp->status."\n");^M Even though it has downloaded the file properly, it is giving the following message: ---=========> /trading/tiscrdenhlist10310000.txt.old, /export/home/crdadm/rajeev/tiscrdenhlist103...

Am getting a pop-up that I need help getting rid of
Name: David Heywood Email: dave.heywood_at_heywoodrealty.com Product: Firefox Summary: Am getting a pop-up that I need help getting rid of Comments: A stupid pop window advertising all kinds of junk keeps popping up that has never popped up before. Can you guys help me figure out where it has planted itself so I can get rid of it. The title line in the box says "Aurora - part of the ABI Network" Thanks Dave Heywood dave.heywood@heywoodrealty.com Browser Details: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3 ...

Where to start and how did you get started?
Hi, I have had a feeling for a long time to jump into the adds market for some time due to my low income (shooting for the stars) and I don't have anything better to do these days. But I find it really difficult not to give up due to lack of guides (what I can find atleast) and all the hard words which only makes me confused. But I won't give up. Never. Not sure if this is the right place to post this, but I deffinitly would be really greatfull for help getting started. How did you get started? +If there are any teacher that wanna show me the ropes private, I can give payment with ...

Two things,Why do I keep getting emails that I don't want. can't get rid of them? Why can't I get my email when I am out of town? Or can I?
Name: Ed Leech Email: ELCraftatzoominternetdotnet Product: Thunderbird Summary: Two things,Why do I keep getting emails that I don't want. can't get rid of them? Why can't I get my email when I am out of town? Or can I? Comments: I am getting frusted with all the emails coming in that I do not want, I am using the tools to get thme out but they keep coming. They just use different names or whatever. I have been thinking of just switching to something else but my business intrusts know this email and it is tooo confusing to change. Every time I go out of town on bu...

Web resources about - Get Rid of Trailing Comma in a String - asp.net.getting-started

Trailing wheel - Wikipedia, the free encyclopedia
On a steam locomotive , a trailing wheel or trailing axle is generally an unpowered wheel or axle ( wheelset ) located behind the driving wheels. ...

Pinterest Now Ranks 3rd, Trailing Twitter And Facebook
That didn't take long: Pinterest is now comfortably in third place in terms of traffic for social networks, trailing Facebook and Twitter.

All sizes - NASA Captures Two Major Hurricanes: Darby Trailing Celia - Flickr - Photo Sharing!
Flickr is almost certainly the best online photo management and sharing application in the world. Show off your favorite photos and videos to ...

Simply stunning: Saints stage revival to beat Bulldogs after trailing by 55 points
&#8203;St Kilda have halted the Western Bulldogs' resurgence with a stunning second-half fight back to seal a thrilling seven-point win.

Silvio Berlusconi trailing Pier Luigi Bersani as Italians head to the polls
Economic Times Silvio Berlusconi trailing Pier Luigi Bersani as Italians head to the polls Herald Sun AUSTERITY-hit Italians take to the polls ...

Polls Have Labor Still Trailing Coalition
Putting too much faith in what the polls say is a flawed strategy.

Ashes 2013: England reaches 7 for 294 at stumps on day three, still trailing Australia by 233 runs
Weather may be the deciding factor in the third Test at Old Trafford, with England 34 runs shy of the follow-on.

PlayStation 4 interest ahead in survey, Wii U trailing behind
Sony's console is riding high in surveys, but will that translate to sales?

Conservatives trailing behind NDP, Liberals in Nanos power index
The federal Conservatives are trailing behind the NDP and Liberals in the latest Nanos poll, with 41 per cent of Canadians saying they would ...

McSally, still trailing, attends orientation
Republican Martha McSally is going through freshman orientation for new U.S. House members in Washington, D.C., this week, despite a growing ...

Resources last updated: 1/22/2016 1:45:49 AM