Reputation: 121
I'm working with some DataGridView's and am having difficulty with manipulating them. I am wanting to trim all the whitespace from the text that's entered into cells but I'm unsure of how to accomplish that.
I've tried using several different events but don't know which is the best one, or if this is even possible. Events I've tried are CellContentChanged
, CellLeave
, CellEndEdit
, CellValueChanged
, and CellValidating
. Aside from not knowing which to use, I also don't know why typical Trim features don't appear to work on cells.
Using something like the code below, in those events, doesn't do the trick.
if (e.ColumnIndex == 1 && dgvApps.CurrentCell.Value != null)
{
string temp = dgvApps.CurrentCell.Value.ToString();
temp.Trim();
}
Trying to catch and prevent keypresses the way that I would in a textbox has also failed.
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
{
e.Handled = true;
}
My endgoal is to check for duplicates and prevent blank entries. Any help would be greatly appreciated.
Upvotes: 1
Views: 803
Reputation:
You can use CellFormatting event like this:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if ( e.Value != null )
e.Value = ( (string)e.Value ).Trim();
}
It will trim the cell input as well as update the bounded data item.
Upvotes: 1