delete a row in a datagrid

Jayesh Acharya
Jayesh Acharya used Ask the Experts™
on
I am trying to delete a specific row in my datagrid, I am able to highlight a row and I can delete a row but the row I delete is always the bottom row of the grid.

I dont know how to pass the information of the row / rows I highlighted to delete

heres is the code i use to delete
        private void deleteRow_Click(object sender, EventArgs ee)
        {
            StockCheckDataTable.Rows[dataGridView1.SelectedRows[0].Index].Delete(); }

dont know how to pass the correct id for the row i highlighted ...
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Jayesh AcharyaTechnichal Consultant

Author

Commented:
ok found the answer

                int yCoord = dataGridView1.CurrentCellAddress.Y;
                StockCheckDataTable.Rows[yCoord].Delete();
Kyle AbrahamsSenior .Net Developer
Commented:
dataGridView1.Rows.Remove(dataGridView1.SelectedRows[0]);
Commented:
int theIndex = this.dataGridView1.CurrentRow.Index;

This is the index of the row you are selecting. You can do whatever you want after having it.
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

Jayesh AcharyaTechnichal Consultant

Author

Commented:
If i highlight multiple rows, is their a way to delete all the rows i highlighted, currently i just delete the last row of all the rows i highlight

Commented:
Then you need to loop through the "SelectedRows" and delete them one by one.
Principal Software engineer
Commented:
Try following

private void DeleteSelectedRows()
        {
            List<DataGridViewRow> rowsWillbeDeleted = new List<DataGridViewRow>(dataGridView1.SelectedRows.Count);
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                rowsWillbeDeleted.Add(row);
            }

            foreach (DataGridViewRow row in rowsWillbeDeleted)
            {
                dataGridView1.Rows.Remove(row);
            }
            rowsWillbeDeleted.Clear();
        }

Open in new window

Jayesh AcharyaTechnichal Consultant

Author

Commented:
Fantastic help easy to understand solutions thnask a lot

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial