[英]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.