I have a simple application where there is a listbox with names of authors in the database (for the purpose of this project 1 author = 1 book). I have to use a typed DataSet for this application.

When you select one of the authors there are three textboxes to the side. One shows the name of the selected author, another one shows the book associated with him, and the last one the date of publishing.

On this form I have 3 buttons. One is supposed to delete the selected row (in the listbox) from the database, one is supposed to update the selected row and one is supposed to insert a new row.

I populated the listbox and textboxes just by using drag and drop from Data Sources onto the form so the only line i have in my code is:

this.BookTableAdapter.Fill(this.myDataSet.Book);

This of course happens on load.

I started with trying to implement the delete function and put this on the onClick event of the delete button:

MyDataSet.BookRow selectedBook = (MyDataSet.BookRow)listBox1.SelectedItem;
selectedBook.Delete();

When I press the delete button it gives me the following exception:

System.InvalidCastException: Unable to cast object of type 'System.Data.DataRowView' to type 'BookRow'.

Can anyone tell me what I am doing wrong here?

有帮助吗?

解决方案

clearly the object in: listBox1.SelectedItem is of type: System.Data.DataRowView so you simply cannot do:

(MyDataSet.BookRow)listBox1.SelectedItem;

the good news is that Delete or Remove methods work with the base class DataRow and DataTable so you don't really need to work at the BookRow type level.

each DataRowView contains a member called Row which returns you the associated DataRow, so you can use that one as your row and delete it directly from there or from the parent DataTable.

I am not compiling the code so cannot say exactly but just try the following and adjust it if does not build fully:

((System.Data.DataRowView)listBox1.SelectedItem).Row.Delete();

其他提示

The list box contains a DataRowView that houses the data bound to it. The problem is with this line MyDataSet.BookRow selectedBook = (MyDataSet.BookRow)listBox1.SelectedItem; Where you are trying to cast a DataRowView to a BookRow object.

Try using the selected value member of the list box or by calling delete on the associated DataRow within the DataRowView of the list box. I'm not sure if delete will actually update the table or just mark a row for deletion so you may have to call update on the datatable/ the deleted row when you're done.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top