Linq to SQL 绑定 ComboBox

最近在练习EF的过程中,实现将Linq返回的结果绑定到Combox时出错。

错误提示如下:

System.NotSupportedException:“Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery, DbRawSqlQuery) is not supported. Instead populate a DbSet with data, for example by calling Load on the DbSet, and then bind to local data. For WPF bind to DbSet.Local. For WinForms bind to DbSet.Local.ToBindingList(). For ASP.NET WebForms you can bind to the result of calling ToList() on the query or use Model Binding, for more information see http://go.microsoft.com/fwlink/?LinkId=389592.”

image

折腾了许久,把查询的结果转换等,最终发现ComBoBox可以绑定Linq查询的结果,唯一的要求就将DataSource放在DisplayMember和ValueMember的后面。

        private void SearchBtn_Click(object sender, EventArgs e)
        {
            //读取表数据并绑定Combox空间
            using (OrderDBContainer db = new OrderDBContainer())
            {
                CBox_User.DisplayMember = "Name";
                CBox_User.ValueMember = "Id";
                CBox_User.DataSource = from u in db.UserAccoutSet 
                                      orderby u.LastName
                                      select new { Name = u.LastName + ", " + u.FirstName, Id = u.Id };
            }
        }

打赏支付宝:

QQ20171114152709_thumb

posted @ 2017-11-14 17:37  孺牛码塔  阅读(929)  评论(2编辑  收藏  举报