The situation is as follows: I have a Database (DB) Department for this database there are two fields id and DepName . Task: by clicking the "Delete" button - remove an object from the Department database and combobox

I fill out the combobox like this:

  try { connection = new SqlConnection(connectionDb); connection.Open(); SqlCommand command = new SqlCommand("SELECT Id, DepName FROM Department", connection); SqlDataReader dr = command.ExecuteReader(); while (dr.Read()) { DepNamesBox.Items.Add(dr[1]); } dr.Close(); command.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.Message); } 

SQL command to delete:

  #region DeleteFunctionDep Query = "DELETE FROM Department WHERE ID = @ID"; command = new SqlCommand(Query, connection); parameter = command.Parameters.Add("@ID", SqlDbType.Int, 0, "ID"); adapter.DeleteCommand = command; #endregion 

"Button":

  DataRowView drv = (DataRowView)DepNamesBox.SelectedItem; drv.Row.Delete(); adapter.Update(dt); 

As a result, the error: System.InvalidCastException: "Could not cast object type" System.String "to type" System.Data.DataRowView "."

Tell me, please, how to correctly remove an object from the database and a combobox or what type DepNamesBox.SelectedItem result DepNamesBox.SelectedItem ?

PS with Listview delete an object turned out to be such a command, but not with a combobox .

    1 answer 1

    DepNamesBox.Items.Add(dr[1]); - Filling control objects directly in the request is not the best approach.
    Separate the presentation from the business logic. Let sql-query return List List<Departments> Keep it in memory and work only with it. And then the matter of several steps:

    1: Bring your object from box to the Department ;
    2: Delete the item first from the database by passing it the Department.id from claim 1;
    3: Delete from the list in memory;
    4: Clean the combobox and give it back to the remaining list items.

    This way you will kill two birds with one stone: simplify the maintenance of your code and make it easier for you to work with the data.