Search code examples
c#parsingdatetimetrim

C#: string.Trim() not removing white spaces


I have a prompt asking user to enter a date (in a specific format). Then I trim the string, however if the there was an extra space when I hit 'Enter' in the prompt box, the string still comes out with an extra space after the trim. I'll post my prompt box code too. My string is: Jul 29, 2015 1:32:01 PM PDT and Jul 30, 2015 12:34:27 PM PDT

    string afterpromptvalue = Prompt.ShowDialog("Enter earliest Date and Time", "Unshipped Orders");
                    afterpromptvalue.Trim();
                    string beforepromptvalue = Prompt.ShowDialog("Enter latest Date and Time", "Unshipped Orders");
                    beforepromptvalue.Trim();

 string format = "MMM dd, yyyy h:mm:ss tt PDT";

            CultureInfo provider = CultureInfo.InvariantCulture;

            afterpromptvalue.Trim();
            beforepromptvalue.Trim();


            DateTime createdAfter = DateTime.ParseExact(afterpromptvalue, format, provider);



            DateTime createdBefore = DateTime.ParseExact(beforepromptvalue, format, provider);

public static class Prompt
{
    public static string ShowDialog(string text, string caption)
    {
        Form prompt = new Form();
        prompt.Width = 500;
        prompt.Height = 150;
        prompt.FormBorderStyle = FormBorderStyle.FixedDialog;
        prompt.Text = caption;
        prompt.StartPosition = FormStartPosition.CenterScreen;
        Label textLabel = new Label() { Left = 50, Top=20, Text=text };
        TextBox textBox = new TextBox() { Left = 50, Top=50, Width=400 };
        Button confirmation = new Button() { Text = "Ok", Left=350, Width=100, Top=70, DialogResult = DialogResult.OK };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(textBox);
        prompt.Controls.Add(confirmation);
        prompt.Controls.Add(textLabel);
        prompt.AcceptButton = confirmation;

        return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
    }
}

Solution

  • string.Trim returns a new string. It does not update the existing variable.

    Strings are immutable--the contents of a string object cannot be changed after the object is created

    https://msdn.microsoft.com/en-us/library/362314fe.aspx

    The proper syntax for your code would be:

    afterpromptvalue = afterpromptvalue.Trim();