我有一个ListView
控件,其中也包含GridView
控件。数据来自不同的表与数据库
数据库方案:
相应的班级分别为Book
,Borrower
和Transaction
。
GridView
抓取
使用数据绑定从这些表中TransactionID
,BorrowerID
,BorrowerName
,BookName
,BorrowDate
和ReturnDate
。
XAML代码:
<Grid>
<ListView Margin="15,57,58,57" Name="borrowedBookList" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding }" KeyDown="borrowedBookList_KeyDown">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Width="80" Header="Borrower ID" DisplayMemberBinding="{Binding Path=BorrowerID}"/>
<GridViewColumn Width="220" Header="Borrower Name" DisplayMemberBinding="{Binding Path=BorrowerName}"/>
<GridViewColumn Width="220" Header="Book Name" DisplayMemberBinding="{Binding Path=BookName}"/>
<GridViewColumn Width="100" Header="Date" DisplayMemberBinding="{Binding Path=BorrowDate}"/>
<GridViewColumn Width="100" Header="Return Date" DisplayMemberBinding="{Binding Path=ReturnDate}"/>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
<Label Content="Borrowed Book List" Height="34" HorizontalAlignment="Left" Margin="310,12,0,0" Name="label1" VerticalAlignment="Top" Width="151" />
<Button Content="Close" Height="31" HorizontalAlignment="Left" Margin="636,535,0,0" Name="close" VerticalAlignment="Top" Width="106" Click="close_Click"/>
<Button Content="Return This Book" Height="31" HorizontalAlignment="Left" Margin="454,535,0,0" Name="return" VerticalAlignment="Top" Width="115" Click="return_Click"/>
</Grid>
现在,我可以选择一行作为Transaction
或Book
或Borrower
的对象吗?我的目标是选择一行并标识Transactions
,Books
表的相应条目,并增加CopyLeft
并将“是”分配到IsReturned
属性中。那我怎么能这样做呢?
另外: 我试着像这样编码:
var selectedTran = this.borrowedBookList.selectedItem as Transaction;
var selectedBook=this.borrowedBookList.selectedItem as Book;
try
{
selectedBook.CopyLeft++;
selectedTran.isReturned="YES";
}
catch(Exception ex)
{
MessageBox.Show(ex.message);
}
异常显示“对象引用未设置为对象的实例”。然后我试图找到借来的BookList的类型:
MessageBox.Show(borrowedBookList.SelectedItem.GetType().ToString());
显示匿名类型。
答案 0 :(得分:0)
您的查询可能会导致匿名类型:
var query = from b in ctx.books
...
select new
{ BorrowerID = b.ID, BorrowerName = b.Name , ...
}
您的网格的selectedItem属性包含此类型,而不是原始实体类。所以我会使用一个命名类,你应该在其中包含主键ID,并使用所选项目中的主键更新相应的实体:
public class ForYourGrid
{
public int BorrowerID { get; set; }
public string BorrowerName { get; set; }
...
}
var query2 = from b in ctx.books
...
select new ForYourGrid
{ BorrowerID = b.ID, BorrowerName = b.Name , ...
}
var selected = this.borrowedBookList.selectedItem as ForYourGrid;
var selectedTran = ctx.Transactions.SingleOrDefault(e => e.TransactionID == selected.TransactionID);
selectedTran.isReturned = "YES";
var selectedBook = ctx.Books.SingleOrDefault(e => e.BookID == selected.BookID);
selectedBook.CopyLeft++;
ctx.SaveChanges();