Right click to select a row in a Datagridview and show a menu to delete it

后端 未结 12 636
梦毁少年i
梦毁少年i 2020-12-02 12:00

I have few columns in my DataGridView, and there is data in my rows. I saw few solutions in here, but I can not combine them!

Simply a way to right-click on a row, i

12条回答
  •  离开以前
    2020-12-02 12:35

    base on @Data-Base answer it will not work until make selection mode FullRow

      MyDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    

    but if you need to make it work in CellSelect Mode

     MyDataGridView.SelectionMode = DataGridViewSelectionMode.CellSelect;
    
     // for cell selection
     private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
     {
      if(e.Button == MouseButtons.Right)
        {
           var hit = MyDataGridView.HitTest(e.X, e.Y);
           MyDataGridView.ClearSelection();
    
           // cell selection
           MyDataGridView[hit.ColumnIndex,hit.RowIndex].Selected = true;
       }
    }
    
    private void DeleteRow_Click(object sender, EventArgs e)
    {
       int rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
       MyDataGridView.Rows.RemoveAt(rowToDelete);
       MyDataGridView.ClearSelection();
    }
    

提交回复
热议问题