在datagridview中搜索并替换特定的单元格值

时间:2013-12-06 06:36:34

标签: c# datagridview replace

我在表单上有一个datagridview1,它包含多少列和数据。在这里,我需要找到包含十进制值“0.04”的特定单元格(例如),单击按钮必须用数字值“0”替换。

我已经尝试过了,

private void button1_Click(object sender, EventArgs e)
{
    string filterBy;
    filterBy = "Stringtext Like '%" + 0.04 + "%'";
    ((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = filterBy;
    int rows = dataGridView1.Rows.Count;
    for (int i = 0; i < rows-1; i++)
    {
        dataGridView1[2, i].Value = dataGridView1[2, i].Value.ToString().Replace(0.04, 0);     
    }
    dataGridView1.Refresh();
}
没有用,任何人都可以帮忙..?

提前感谢..

1 个答案:

答案 0 :(得分:0)

我不会像你一样以艰难的方式去做。我就是这样做的:

private void button1_Click(object sender, EventArgs e)
{
    int countColumn, intCell = -1, intRow = -1;

    countColumn = dataGridView1.Columns.Count;

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        intRow++;

        foreach (DataGridViewCell c in row.Cells)
        {
            //if (c.Value == null) { continue; }
            if (c.Value?.ToString() != "0.04") { continue; }

            intCell = +1;
            dataGridView1.Rows[intRow].Cells[intCell].Value = "0";

            if (intCell == countColumn)
            {
               intCell = -1;
            }
        }
    }
}