views:

803

answers:

1

Hello,

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, it will select the whole row and show a menu with an option to delete the row and when the option selected it will delete the row

I made few attempts but none is working and it looks messy

any suggestions?

cheers

+2  A: 

Hello,

I finally solved it :-)

first in Visual Studio create a ContextMenuStrip with an item called "DeleteRow"

then at the DataGridView link the ContextMenuStrip

using the code below helped me getting it work :-)

this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
this.DeleteRow.Click += new System.EventHandler(this.DeleteRow_Click);

here is the cool part

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Right)
            {
            var hti = MyDataGridView.HitTest(e.X, e.Y);
            MyDataGridView.ClearSelection();
            MyDataGridView.Rows[hti.RowIndex].Selected = true;
            }
        }

private void DeleteRow_Click(object sender, EventArgs e)
        {
            Int32 rowToDelete = MyrDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
            MyDataGridView.Rows.RemoveAt(rowToDelete);
            MyDataGridView.ClearSelection(); 
        }

Hope the code will help others :-)

I welcome any correction if there is an error

cheers

Data-Base