How do I trim my values in a gridview edit form before they are updated or inserted into the database? I want to be sure that users do not add extra spaces onto the end of the text or at the begining.

Use the String.Trim method E.g.

string x = "    test   ";
x.Trim(); //<- removes spaces from start and end
System.Diagnostics.Debug.WriteLine(x); // x it now "test"

Where does this code go? In the datasource? the datasource parameters? the gridview?

I am able to trim the insert values via code behind:

string firstName = ((TextBox)mainGridView.FooterRow.FindControl("insertFirstName")).Text.Trim();

However, this is not working for my update command. It's almost as if my code behind is being ignored and default UpdateParameters are being used.

Sorry, I thought you were using DataGridView. someString.Trim(); returns a string but it doesn't change that string from which it is called.

Replace your code with this:

((TextBox)mainGridView.FooterRow.FindControl("insertFirstName")).Text = ((TextBox)mainGridView.FooterRow.FindControl("insertFirstName")).Text.Trim();

Thanks

Edited 6 Years Ago by farooqaaa: n/a

Still unable to get this to work. My latest attempt, putting the following in the RowUpdating event.

((TextBox)mainGridView.Rows[mainGridView.EditIndex].FindControl("editFirstName")).Text = ((TextBox)mainGridView.Rows[mainGridView.EditIndex].FindControl("editFirstName")).Text.Trim();
This article has been dead for over six months. Start a new discussion instead.