Question:
How do you make a comma delimited string from a multi select listbox?
SweetCheeks
2009-03-20 06:50:40 UTC
I have a listbox on a page where the user can select multiple names (Name). The list is ordered by NameID int.

How do I go through each item, and if it's selected, add the NameID to the string, with each one being separated by a comma. I plan on using this string to insert multiple rows in a second table in my database.

for example:

ListItem li = new ListItem();
foreach ( ListItem li in lstNewAnalyst.Items )
{
if ( li.Selected = true )
{
//What goes here to make a string comma delimited string?
}
}

Thanks much! ^__^
Three answers:
ajayx2001
2009-03-20 08:21:22 UTC
string str;

foreach(ListItem li in lstNewAnalyst.Items) {

if(li.Selected = true) {

str += li.toString() + ", ";

}

}



That should do it.
2009-03-20 07:32:27 UTC
You want a separate Insert statement for each selection if you want to insert multiple rows, so:



strSQL = "INSERT INTO (NameID, ) VALUES (, '" + li + "') ;";



Then do the actual insert into the database (execute the insert string on the connection by whatever method you're using to manipulate the database).



Making one long comma-delimited string would insert one row with lots of fields. If you need a comma-delimited string, though, if the string isn't null, add a comma, then add the current element. That gives you a comma after every element but the last one. (If there might be commas in the data itself - like names and addresses, add a quote, add the data from the listbox, add a quote, then add a comma.)
2009-03-20 07:04:39 UTC
something around the lines of:



someVariable .= li.value+',';



I'm a PHP guy so I don't know syntax, but it'll be like that.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...