Juste3alfaz
Juste3alfaz

Reputation: 295

ContextMenuStrip don't recognize the selcted item in List

I have ContextMenuStrip to show 2 Menu Item, and I use it on DataGridViewRow. I have a checkBoxColumn to select just 1 row to take an Id and used in another function. So this is my code to selrct the rows.

//get the selected item
List<DataGridViewRow> selectedRows = (from row in Detail_shanuDGV.Rows.Cast<DataGridViewRow>()
                                      where Convert.ToBoolean(row.Cells["checkBoxColumn1"].Value) == true
                                      select row).ToList();

if ((selectedRows.Count > 1) || (selectedRows.Count == 0))

    MessageBox.Show("Plz select au moin un ligne...");
else
{
    foreach (DataGridViewRow row in selectedRows)
    {
        //to do functions
    }
}

If I try used this code it always give me MessageBox.Show("Plz select au moin un ligne..."); but if I select another row it will show the last row selected.

My problems here that this code not working with ContextMenuStrip or MenuStrip, it works only with buttons.

Upvotes: 1

Views: 42

Answers (1)

Juste3alfaz
Juste3alfaz

Reputation: 295

Thanks to Reza Aghaei and his post here
I have my problems because the edited cell value is not committed to the DataSource until it's validated, which happens when the cell lose focus. If you want to commit the modifications immediately, you can handle the CurrentCellDirtyStateChanged event, and call the CommitEdit method in the handler : So, If for any reason you want to push changes sooner, you can call:

dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);

This method commits every change just after the change is made.

So, for my code I add the code before selected item and it works, and the location of the commit is very important and preferred to put it in CellContentClick

    //get the selected item
Detail_shanuDGV.CommitEdit(DataGridViewDataErrorContexts.Commit);
List<DataGridViewRow> selectedRows = (from row in Detail_shanuDGV.Rows.Cast<DataGridViewRow>()
                                      where Convert.ToBoolean(row.Cells["checkBoxColumn1"].Value) == true
                                      select row).ToList();

if ((selectedRows.Count > 1) || (selectedRows.Count == 0))

    MessageBox.Show("Plz select au moin un ligne...");
else
{
    foreach (DataGridViewRow row in selectedRows)
    {
        //to do functions
    }
}

Upvotes: 1

Related Questions