0

I have been trying to remove duplicate whitespace from textbox before the data is submitted to database. I have tried TRIM() function in MySQL, like

cmd.CommandText = "INSERT INTO table1 VALUES TRIM(('" + textBox1.Text + "', '" + textBox2.Text + "'))";

it did not work. I also tried this

textBox1.Text = textBox1.Text.Replace("  ", " ");

I added above code to the submission button which works but it only removes whitespace if it appears twice, as in, double space. In a case where the user input more than two spaces, how do I implement it?

For example: "Hello World" should be submitted as "Hello World"

Spythonian
  • 197
  • 1
  • 7

3 Answers3

1

Try this:

stextBox1 = textBox1.Text;

RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);     
textBox1.Text = regex.Replace(stextBox1 , " ");

Got is from How do I replace multiple spaces with a single space in C#?

You need to add the line: using System.Text.RegularExpressions; under using System; below is an example in c# that works:

using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string stextBox1 = textBox1.Text;

            RegexOptions options = RegexOptions.None;
            Regex regex = new Regex("[ ]{2,}", options);
            textBox1.Text = regex.Replace(stextBox1, " ");
        }
    }
}
zip
  • 3,938
  • 2
  • 11
  • 19
  • Add Trim to remove all white space from beginning and end, its only in the middle the OP want to collapse multiple to one. – David Mårtensson Dec 09 '19 at 16:00
  • Thanks @zip. This doesn't work. I am having lots of errors. Just started programming, not good at regular expression. Any tips? – Spythonian Dec 09 '19 at 16:32
0

try this code with regular expression :

        string str = textBox1.Text;
        str = Regex.Replace(str, @"\s", "");
Marwen Jaffel
  • 703
  • 1
  • 6
  • 14
0

This should result is what you want to achieve:

string str = textBox1.Text;
str = Regex.Replace(str, @"\s+", " ");
Dekryptid
  • 1,062
  • 1
  • 9
  • 21