开发者

Exception handling in WPF data binding

Let's say I have the following code in WPF application:

try
{
   // NorthwindDataContext is LINQ DataContext created for SQL Server Northwind database
   Data.NorthwindDataContext data = new Data.NorthwindDataContext(connectionString);

   var orders = from order in Data.Orders select order;

   listView.DataContext = orders;
}
catch (SqlException ex)
{
   MessageBox.Show(ex.Message);
}

If connectionString is incorrect, this code doesn't throw SqlException immediately. Instead of this, exception is thrown later, whe开发者_开发百科n WPF data binding starts to enumerate LINQ query. Application crashes with unhandled exception. How can I handle exception in such situation?

I know that it is possible with global exception handling, but I want more precise way, which allows to catch specific exception when specific function is executed.


This is the curse of the Linq and not data binding.

Your query has been compiled but not run - you are binding to a query not the result. Change to the following code:

var orders = from order in Data.Orders select order;
var realOrders = orders.ToList();
listView.DataContext = realOrders ;

Basically your repository must always return results and not raw queries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜