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

后端 未结 12 676
梦毁少年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:25

    See here it can be done using the DataGridView RowTemplate property.

    Note: This code isn't tested but I've used this method before.

    // Create DataGridView
    DataGridView gridView = new DataGridView();
    gridView.AutoGenerateColumns = false;
    gridView.Columns.Add("Col", "Col");
    
    // Create ContextMenu and set event
    ContextMenuStrip cMenu = new ContextMenuStrip();
    ToolStripItem mItem = cMenu.Items.Add("Delete");
    mItem.Click += (o, e) => { /* Do Something */ };           
    
    // This makes all rows added to the datagridview use the same context menu
    DataGridViewRow defaultRow = new DataGridViewRow();
    defaultRow.ContextMenuStrip = cMenu;
    

    And there you go, as easy as that!

提交回复
热议问题