[英]Linq-to-sql to Combobox binding (Winforms)
我有一个WinForm。 在此表单中,我显示表行中的数据。 我有表评论和用户:
评论:{ID(int),Text(NVarchar),UserId(int)}
用户:{ID(int),名称(NVarChar)}
在表单上,我有TextBox和Combobox。 在“文本框”中,我不会显示“注释”中的“文本”(用户可以编辑此字段,数据必须保存在表中)和“表”用户中的名称(其中Comment.UserId = Users.ID)。
我有以下代码:
FormDataClassesDataContext dc = new FormDataClassesDataContext();
_comment = (from comment in dc.Comments
where comment.ID == 1
select comment).FirstOrDefault();
_user = (from users in dc.Users
where users.ID == _comment.UserId
select users).FirstOrDefault();
textBoxComment.DataBindings.Add("Text", _comment, "Text"); // <-OK
comboBoxAssessor.DataSource = dc.Users;
comboBoxAssessor.DisplayMember = "Name";
comboBoxAssessor.ValueMember = "ID";
comboBoxAssessor.DataBindings.Add("SelectedItem", _comment, "UserId");
接着
dc.SubmitChanges();
但我变成“无法将“ MyApp.Forms.User”传递给“ Int32”
组合框的选定项目是其数据源中的当前对象,在这种情况下为: User
。 您必须使用SelectedValue
:
comboBoxAssessor.DataBindings.Add("SelectedValue", _comment, "UserId");
它返回您在ValueMember
定义的属性的ValueMember
。
如果我没有记错的话,SelectedItem的类型应该为User。 然后将Comment.UserId(int)绑定到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.