简体   繁体   English

从组合框中的选定项目获取数据库行

[英]Get database row from selected item in Combobox

I have a Combobox which gets its data from my database. 我有一个组合框,可从我的数据库中获取其数据。

var people = (from x in db.Person select new { Value = x.Id, Names = x.Namn + " " + x.EfterNamn }).ToList();
cbpeople.DataSource = people;
cbpeople.DisplayMember = "Names";
cbpeople.ValueMember = "Value";
cbpeople.SelectedIndex = -1;

And I have the SelectedIndex function 我有SelectedIndex函数

int id = cbpeople.SelectedIndex + 1;
string namn = (from x in db.Person where x.Id == id select x.Namn).ToString();
lblNamn.Text = namn;

So as you can see, I'm trying to have it select the information from the same row in the database and put them in labels. 如您所见,我正在尝试让它从数据库的同一行中选择信息,并将其放入标签中。 (The "cbpeople.SelectedIndex + 1;" is because I had no other way to get the ID from the SelectedValue). (“ cbpeople.SelectedIndex + 1;”是因为我没有其他方法可以从SelectedValue中获取ID)。

But all it prints out is this long thing instead of the Name (on the label) 但是打印出来的只是这个长东西,而不是名称(在标签上)

"SELECT \r\n    [Extent1].[Namn] AS [Namn]\r\n    FROM [dbo].[Person] AS [Extent1]\r\n    WHERE [Extent1].[Id] = @p__linq__0"

What am I doing wrong? 我究竟做错了什么?

You calling ToString() over IQueryable object. 您通过IQueryable对象调用ToString()。 Of course, it will return it's SQL representation. 当然,它将返回它的SQL表示形式。 To execute query you can do this: 要执行查询,您可以执行以下操作:

string namn = (from x in db.Person where x.Id == id select x.Namn).Single();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM