views:

356

answers:

1

I have developed a Windows Forms application and it has a datagrid with checkbox. If I press a button then I want to get all checked rows and do some operation on them. The problem is that when button is pressed it does not recognize the latest checkbox action. It is like one step behind.

My code is:

    private void copyToToolStripMenuItem_Click(object sender, EventArgs e)
    {
        dataGridView1.ClearSelection();
        DialogResult result = this.folderBrowserDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            string foldername = this.folderBrowserDialog1.SelectedPath;
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.Cells[0].Value != null)
                {
                    if ((bool)row.Cells[0].Value == true)
                    {
                        try
                        {
                            string[] vars = row.Cells[1].Value.ToString().Split('\\');
                            System.IO.File.Copy(row.Cells[1].Value.ToString(), foldername + @"\" + vars[vars.Length - 1], true);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                }
            }
        }
    }

Data is from a SQL query - the usual stuff.

+1  A: 

Roland,

The reason could be because the data has not yet been committed to the source. The way the DataGridView works is that it is 'bound' to a source and it keeps the data synchronized. However changes made in the DataGridView don't update the DataGridView straight away. It is considered 'Dirty'.

Try checking the original data source after the change, you could also try calling BindingContext(..).EndCurrentEndit(); or something similar to try and ensure data is committed.

Ian
Adding dataGridView1.EndEdit(); solved the problemTanks!
Woland