Click here to Skip to main content
15,916,180 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
here when i am calling address column from controler and view its coming in a row but i want to make next line after 3 commas

like address

sar john,texas,dellas,ny,111111,
the output should come
sar john,texas,dellas
ny,11111

i am using mvc rozer file
Posted

Hi,

Iam not into MVC stuff.
But normally i guess u can to a charindex for your 3rd comma and replace by \n when binding the data to your row.

Hope this helps.
Happy coding.
 
Share this answer
 
This Method would split the given String every newLineEvery fields (separated columns by comma)

C#
public string FixAddress(string address, int newLineEvery = 3){
	if(String.IsNullOrEmpty(address))
		return address;
	string separator = ",";
	string newAddress = String.Empty;
	if(address.Contains(separator)){
		int elemCount = 0;
		foreach(string elem in address.Split(separator)){
			elemCount++;
			newAddress += (elemCount % newLineEvery == 0) ? "\n"+elem : elem; 
		}
		return newAddress;
	}
	return address;
}


Also behavior would be different if you are actually using MvcHtmlString instead of a string field here. (Html Linebreaks are different and also you would need to utilize MvcHtmlString.Create(newAddress) as Return of the function.
 
Share this answer
 
v2
You may take the following approach-
1. Find the index of 3rd comma from the supplied string variable
C#
public int GetNthIndex(string s, char t, int n)
{
    int count = 0;
    for (int i = 0; i < s.Length; i++)
    {
        if (s[i] == t)
        {
            count++;
            if (count == n)
            {
                return i;
            }
        }
    }
    return -1;
}

Reference: Find Nth occurrence of a character in a string

2.Remove the comma & add carriage return character after that index like
C#
string yourString="sar john,texas,dellas,ny,111111,";
string finalString;
finalString=yourString;
int indexOfThirdIndex=0;
int counter=3;
while(indexOfThirdIndex!=(-1))
{
   int indexOfThirdIndex=GetNthIndex(finalString,',',counter);
   if(indexOfThirdIndex!=(-1))
   {
      finalString=finalString.Substring(0, indexOfThirdIndex).TrimEnd(',')+"\r\n"+inalString.Substring(indexOfThirdIndex);
   }
   counter+=3;
}


Hope, it helps :)
N:B: I haven't tested all these in my system but the approach should work. Please let me know if it doesn't.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900