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 .