简体   繁体   中英

Search and replace specific cell value in a datagridview

I have a datagridview1 on a form, which contains number of columns and data. Here I need to find specific cells which contains the decimal value of "0.04" (for example), must be replaced with the numeric value of "0" by clicking single button.

I have tried already this,

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

no use, can anyone help..?

thanks in advance..

I wouldnt do it the hard way, like you. This is how i would do it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM