Search code examples
c#asp.nettrim

textbox text trim allow 1 blankspace asp net c#


I have a textbox that I want to allow 1 blank space. So right now, the trim method does not allow it, but is there anyway to allow 1 blank space?

C#:

bool before = txtSearchFor.Text.StartsWith(" ");
bool after = txtSearchFor.Text.EndsWith(" ");
string newText = before && after
                 ? txtSearchFor.Text.Trim() + " "
                 : before ? " " + txtSearchFor.Text.TrimStart() : after ? txtSearchFor.Text.TrimEnd() + " " : txtSearchFor.Text;

var contacts = SearchNRender(ExtCatIdentifier.All.ToString(), txtSearchFor.Text = newText);
var searchFormat = string.Format("[ {0} ]", txtSearchFor.Text);

Solution

  • bool before = txtSearchFor.Text.StartsWith(" ");
    bool after  = txtSearchFor.Text.EndsWith(" ");
    string newText = before && after 
                     ? txtSearchFor.Text.Trim() + " " 
                     : before ? " " + txtSearchFor.Text.TrimStart() : after ? txtSearchFor.Text.TrimEnd() + " " : txtSearchFor.Text;
    
    txtSearchFor.Text = newText;