Create a Comma Separated String from A List of String in asp.net
.cs File Code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. public partial class UserControls_CommaSeparatedControl: System.Web.UI.UserControl {
  8. // Declaring List as static
  9. static List < string > strList = new List < string > ();
  10. protected void Page_Load(object sender, EventArgs e)
  11. {
  12. if (!IsPostBack) {
  13. // Clearing the List ob its first load
  14. strList.Clear();
  15. }
  16. }
  17. protected void BtnSave_Click(object sender, EventArgs e)
  18. {
  19. CreateListOfString();
  20. }
  21. private void CreateListOfString()
  22. {#region--Create list of string--
  23. try
  24. {
  25. if (txtSomeText.Text != "")
  26. {
  27. strList.Add(txtSomeText.Text);
  28. txtSomeText.Text = "";
  29. }
  30. GridView1.DataSource = strList;
  31. GridView1.DataBind();
  32. string Result = GetSeparateTheString(strList, ", ");
  33. LblResult.Text = Result;
  34. }
  35. catch (Exception Exc)
  36. {
  37. LblMessage.Text = "Application Error : " + Exc.Message;
  38. }
  39. #endregion
  40. }
  41. private string GetSeparateTheString(List < string > strList, string comma)
  42. {#region--Create a Comaa Separated string--
  43. try
  44. {
  45. System.Text.StringBuilder sb = new System.Text.StringBuilder();
  46. foreach(string str in strList)
  47. {
  48. // If this statement found any value in the String Builder Object, it will add comma one after another.
  49. if (sb.Length > 0)
  50. {
  51. sb.Append(comma);
  52. }
  53. // in its first pass it will take the first string , then others string: because this line must execute
  54. sb.Append(str);
  55. }
  56. return sb.ToString();
  57. } catch (Exception Exc)
  58. {
  59. LblMessage.Text = "Application Error : " + Exc.Message;
  60. return "";
  61. }
  62. #endregion
  63. }
  64. }