Reputation: 2523
I have a form on which you can select multiple items to create a code.
Eg. if I clicked on "name", it would add that to the string, then if I clicked "age" it would then add that to the string, but if I unchecked "name", it would remove it from the string.
I have no idea of how to go about this. Can someone help?
Upvotes: 0
Views: 67
Reputation: 936
Why not using List? it allows you to add/remove elements easily? if you click on name, just add it to the list, when you uncheck the name, remove it from the list, after that, you can convert your list into a string and use it.
//Add string
var myList = new List<string>();
//After clicking:
myList.add(clickedElement);
//After uncheck
myList.remove(uncheckedElement);
//At the end, just convert your list to string to use it
var myString = string.Join(" ", myList.ToArray());
Upvotes: 0
Reputation: 11233
Take a List<string>
and add/remove items to/from the list. Once you are done, you make a call to string.Join
and construct a single string from array.
List<string> items = new List<string>(); // declare globally
private void add(string item)
{
items.Add(item);
}
private void remove(string item)
{
items.Remove(item);
}
private string convertArrayToString(string delimiter, List<string> elements)
{
delimiter = (delimiter == null) ? "" : delimiter;
return string.Join(delimiter, elements.ToArray());
}
Note:
Giving a priority to List<T>
over string[]
would be a good decision since, here collection would be resize. Have a look at this discussion which can help you on this.
Upvotes: 1