Home > Blockchain >  C# Winform: How to show context menu just below the datagrid button
C# Winform: How to show context menu just below the datagrid button

Time:10-27

I have grid and one column type is button column. i want that when user click on button then menu should show just below the button but i am not able to achieve this. dgList is name of datagridview. if there is no space to show the menu then menu position will be adjusted dynamically.

here is my code what i tried

private void Form1_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("ID", typeof(int));
    dt.Columns.Add("Name", typeof(string));
    dt.Columns.Add("Salary", typeof(int));

    DataRow dr = null;
    dr = dt.NewRow();
    dr[0] = 1;
    dr[1] = "Joydip";
    dr[2] = 5200;
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0] = 2;
    dr[1] = "Salim";
    dr[2] = 3200;
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0] = 3;
    dr[1] = "Sukumar";
    dr[2] = 6000;
    dt.Rows.Add(dr);

    dgList.AutoGenerateColumns = false;
    dgList.DataSource = dt;
    dgList.Columns[0].DataPropertyName = "ID";
    dgList.Columns[1].DataPropertyName = "Name";
    dgList.Columns[2].DataPropertyName = "Salary";

}

private void dgList_MouseClick(object sender, MouseEventArgs e)
{
    int currentMouseOverRow = dgList.HitTest(e.X, e.Y).RowIndex;
    if (currentMouseOverRow >= 0)
        contextMenuStrip1.Show(dgList, new Point(e.X, e.Y));
        
}

I tried also this code but no luck.

private void dgList_MouseClick(object sender, MouseEventArgs e)
{
    DataGridViewCell currentCell = (sender as DataGridView).CurrentCell;
    if (currentCell != null)
    {
        ContextMenuStrip cms = currentCell.ContextMenuStrip;
        Rectangle r = currentCell.DataGridView.GetCellDisplayRectangle(currentCell.ColumnIndex, currentCell.RowIndex, false);
        Point p = new Point(r.X   r.Width, r.Y   r.Height);
        contextMenuStrip1.Show(currentCell.DataGridView, p);
    }
}

please guide me what mistake is there in my code. how to achieve what i am looking for.

Thanks

CodePudding user response:

Issue fixed. here the working code

private void dgList_MouseClick(object sender, MouseEventArgs e)
{
    DataGridViewCell currentCell = (sender as DataGridView).CurrentCell;
    if (currentCell != null && currentCell.ColumnIndex==3)
    {
        ContextMenuStrip cms = currentCell.ContextMenuStrip;
        Rectangle r = currentCell.DataGridView.GetCellDisplayRectangle(currentCell.ColumnIndex, currentCell.RowIndex, false);
        Point p = new Point(r.X, r.Y   r.Height);
        contextMenuStrip1.Show(currentCell.DataGridView, p);
    }
}
  • Related