Question

I have a DataGridView linked to a ContextMenuStrip. The DataGridView is populated. I select a row (any cell) and when I right click, it opens a menu, where I can choose Edit, Rename or Delete. How can I pass the row number of the selected row to my ContextMenuStrip? So, I left click to select a cell in Row Number 2. I right click anywhere on the DataGridView and I select "Rename". I want to get a message "you want to rename row number 2". It would be ok to right-click directly on row number 2 and get the message (without first selecting a cell on row number 2).Here is my attempt of code:

void RenameToolStripMenuItemClick(object sender, EventArgs e)
{ //this should rename the table
    MessageBox.Show("This should rename the selected row number " + dataGridView1.SelectedRows.ToString());
}
Was it helpful?

Solution

You will need to look at the RowIndex property for the CurrentCell property for the DataGridView. some thing like

void RenameToolStripMenuItemClick(object sender, EventArgs e)
{ //this should rename the table
    MessageBox.Show("This should rename the selected row number " + dataGridView1.CurrentCell.RowIndex);
}

BUT please remember RowIndex count is starting at 0.

So, row one will show row number 0 and row two will show row number 1.

To work around the RowIndex confusion, you could just add a 1 to the rowIndex like below

void RenameToolStripMenuItemClick(object sender, EventArgs e)
{ //this should rename the table
    MessageBox.Show("This should rename the selected row number " + (dataGridView1.CurrentCell.RowIndex + 1));
}

OTHER TIPS

On the datagridview add event: " MouseDown " At the form, create a global integer variable;

        try
        {
            if (e.Button == MouseButtons.Right)
            {
                dtg_contatos.ClearSelection();
                var hti = dtg_contatos.HitTest(e.X, e.Y);
                dtg_contatos.Rows[hti.RowIndex].Selected = true;
                selected_row = hti.RowIndex;
            }
        }
        catch
        {
        }

Now, at the ContextMenuStrip, add CLickEvent

        string verificacao = dtg_contatos.Rows[selected_row].Cells[0].Value.ToString();
        if (verificacao != "")
        {
            int codigo = int.Parse(dtg_contatos.Rows[selected_row].Cells[0].Value.ToString());
        }

I supposed the cod are on the first cell, then you get the data to work with what you want, one time that ou have the cod you can do everything.

Subscribe to the DataGridView.CellMouseDown event. In the event handler, shows the required context menu.

Sample Code:

void myDGV_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            //get the rowindex or columnindex from the event argument and show the context menu.
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top