Search code examples
c#datagridviewcontextmenustrip

datagridview contextmenustrip : showing only for chosen rows?


I have standard datagridview and I have contextmenustrip. My problem is that I need to show this contextmenustrip when user click right mouse button but not on every row! Only on rows I've chosen. I tried this:

dataGridView1.Rows[1].ContextMenuStrip = contextMenuStrip1;

But it doesn't work.


Solution

  • Sounds to me like you want to open your ContextMenuStrip if your user right clicks the header of your DataGridView's column that satisfies some condition.

    In short: use the DataGridView MouseDown event and in that event check for the conditions and if they're met call the Show method of your ContextMenuStrip.

    Code sample that you may refer:

    private void dataGridView1_MouseDown(object sender, MouseEventArgs e) {
        if (e.Button == MouseButtons.Right) {
            var ht = dataGridView1.HitTest(e.X, e.Y);
            // Place your condition HERE !!!
            // Currently it allow right click on last column only
            if ((    ht.ColumnIndex == dataGridView1.Columns.Count - 1) 
                 && (ht.Type == DataGridViewHitTestType.ColumnHeader)) {
                // This positions the menu at the mouse's location
                contextMenuStrip1.Show(MousePosition);
            }
        }
    }