Click here to Skip to main content
16,012,468 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
Hi developer's
I want replace regular expressions from DataGridView all columns and rows, for that I am using a regex, but its provide an error.

please check this code and solve the problem its my request.
private void button2_Click(object sender, EventArgs e)
 {
   char comma = ',';
   char slash = '/';
   char colon = '"';
   string Blank = "";

   try
    {
      foreach(DataGridViewRow datarow in dataGridView1.Rows)
       {
        foreach(DataGridViewCell datacol in dataGridView1.)
          {
             datarow[datacol] = System.Text.RegularExpressions.Regex.Replace(comma.ToString(),slash.ToString());
                   datarow[datacol] = System.Text.RegularExpressions.Regex.Replace(colon.ToString(),Blank.ToString());
          }
       }
    }
   catch(System.Exception ex)
    {
       MessageBox.Show(ex.Message);
     }
 }
Posted
Updated 8-Dec-10 20:16pm
v2
Comments
TweakBird 9-Dec-10 2:16am    
code blocks fixed.
Dave Kreskowiak 9-Dec-10 10:20am    
You forgot to post the most important piece of information to diagnose your problem. What's the error message??
Dr.Walt Fair, PE 10-Dec-10 19:55pm    
Do you really mean colon = '"'? Normally a colon should be ':'

As Dave asked, what's the error message and where does it happen?

1 solution

There are several syntax errors with your posted code, which I attempted to correct based on assumptions. Also, as noted in the comments, a colon is normally this character: ':'.

One thing that's important to note is that when iterating over a collection, you'll get an exception if you change any members in the collection. Therefore, you'll want to use a for loop to iterate over the cells in the DataGridView if you want to edit the indivdual cells values.

See if the code below works for you.
private void button2_Click(object sender, EventArgs e)
{
    char comma = ',';
    char slash = '/';
    char colon = '"';
    string Blank = "";
    try
    {
        for (int row = 0; row < dataGridView1.Rows.Count;row++ )
        {
            for (int column = 0; column < dataGridView1.Columns.Count; column++)
            {
                object value = dataGridView1[column, row].Value;
                if (value != null && value.GetType() == typeof(string))
                {
                    string newValue = (string)value;
                    newValue = newValue.Replace(comma,slash);
                    newValue = newValue.Replace(colon.ToString(),Blank);
                    dataGridView1[column, row].Value = newValue;
                }
            }
        }
    }
    catch(System.Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900