0

I am writing a C# program right now that uses a datatable that is connected to a SQL database. I need to allow the program to delete the highlighted row from both the program and the database. Right now I have a working event on key press delete that runs a SQLcommand to remove the entry, however, it removes all entries and not the selected row (this is due to a different problem). Basically, I am wondering how I can return what row is currently highlighted. If I can return that number then I can continue on with my program.

For example, I have data in the first 5 rows of the datatable but id like to highlight(by clicking) and delete the 3rd row. If I can return the third row then I can write a different SQL statement to handle based off of a different set of criteria.

Thanks.

G3TH
  • 247
  • 4
  • 14
  • 2
    What is your table schema? What is your delete query? Use some unique ID which tells you what row to remove (e.g. autoincremenet, sequence or guid). Why don't you use some ORM which will do query for you? – Klaudiusz bryjamus Nov 13 '15 at 20:02
  • I think most people would bind the DataTable to a grid of some kind and let its delete method handle those things. I'd give suggestions but you didn't say if winforms or web forms or mvc or what you're using. =) – Nikki9696 Nov 13 '15 at 20:06
  • Can you show the event that you are doing this in ..? also how come you can't just do something as simple as this on the `DataGrids's SelectedChanged` event `var selectedIndex = YourDataGrid.SelectedRows[0].Index;` amazing what google can produce when doing a simple search http://stackoverflow.com/questions/11260843/getting-data-from-selected-datagridview-row-and-which-event – MethodMan Nov 13 '15 at 20:07
  • Methodman: I was able to solve my problem with a mix of a couple things. First was changing the Datagridview selectionmode to FullRowSelect. That was what I was attempting to ask but wasn't sure how to word. After that was set I used the reference you gave to write the rest of the code and it now works. Thank you. – G3TH Nov 17 '15 at 23:35

1 Answers1

1

Assume you use a Bindingsource to load data into Datagridview:

if(myBindingSource.Current != null)
{
  myBindingSource.RemoveCurrent();
  myBindingSource.EndEdit();
}
vaheeds
  • 2,594
  • 4
  • 26
  • 36