1

I have to use SqlDataAdapter in this issue. Why this code doesn't want to delete a specified row?

There are no errors, script is entering to if statement.

id_book is correct, table name: Book

        public static void DeleteBook(int id_book)
        {
            using (var connection = new SqlConnection(DbCon.ConnectionString))
            {
                connection.Open();
                var adapter = new SqlDataAdapter("SELECT * FROM Book", connection);
                var builder = new SqlCommandBuilder(adapter);
                var table = new DataTable();
                adapter.Fill(table);

                var rowToDelete = table.Select($"id_book = {id_book}").FirstOrDefault();
                if (rowToDelete != null)
                {
                    table.Rows.Remove(rowToDelete);
                    adapter.Update(table);
                }
            }
        }

DELETE FROM Book WHERE id_book = 20; -> works correctly in DB

kacprodyl
  • 23
  • 2
  • 1
    Not an answer to the question, but: using `DataAdapter` and `DataTable` is *very* old school, and should basically not be done for new work unless you have an actual use case with fully dynamic table structures (where `DataTable` still has some defensible use, despite its considerable memory overhead). From a more friendly O-O approach to maintaining entities, check out things like Entity Framework; for lightweight database operations without the overhead of boilerplate, look at things like Dapper. – Jeroen Mostert Mar 28 '23 at 18:41
  • 2
    @ThomasWeller it does. If it cannot find any -matching elements if you provide a predicate- it will return default value of the type, which is null for any reference type. It would be better to check if the returned value is default. I mean: if (rowToDelete != default) – cemahseri Mar 28 '23 at 18:55
  • https://stackoverflow.com/questions/4302052/remove-row-through-dataadapter You have to DELETE rather than REMOVE – Poutrathor Mar 29 '23 at 12:35

0 Answers0