替换datagridview单元中的值 [英] replace values from datagridview cells

查看:86
本文介绍了替换datagridview单元中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好开发者的
我想从DataGridView的所有列和行替换正则表达式,因为我正在使用正则表达式,但是它提供了错误.

请检查此代码,并解决其问题.

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);
     }
 }

推荐答案

您发布的代码中存在一些语法错误,我尝试根据假设进行纠正.另外,如评论中所述,冒号通常是以下字符::".

需要注意的一件事是,当迭代集合时,如果更改集合中的任何成员,您将获得异常.因此,如果要编辑单个单元格的值,则需要使用for循环来遍历DataGridView中的单元格.

查看下面的代码是否适合您.
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);
    }
}


这篇关于替换datagridview单元中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆