Removing Non-Numeric Characters from a String

09.21.07

Problem: I have an editable grid that needs to contain numeric integer values only.

My Solution: TryParse, this function accepts a string and an out value then returns a  bool True if it was successful, also it does not throw exceptions. I am a 100% sure there is someone with a better way of doing this but this is what I came up with. Feedback encouraged!

private string RemoveNonNumericValues(string p)
{
     int tempValue = 0;
     StringBuilder value = new StringBuilder(p.Length);
     foreach (char charValue in p.ToCharArray())
     {
         if (int.TryParse(charValue.ToString(), out tempValue))
             value.Append(tempValue.ToString());
     }
     return value.ToString();
}
private void dataGrid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    dataGridView[e.ColumnIndex, e.RowIndex].Value = RemoveNonNumericValues(dataGridView[e.ColumnIndex, e.RowIndex].Value.ToString());
}