[英]Retrieving value from combobox Winforms / Entity Framework
我正在嘗試用公司列表填充組合框,然后將所選公司的值(其Id
)獲取到我的數據庫中。
我有此類CBItem
:
public class CBItem
{
public string Name { get; set; }
public int Value { get; set; }
public override string ToString()
{
return Name;
}
}
我使用以下方法將項目添加到組合框:
using (var db = new DataContext())
{
var list_of_companies = db.Companies;
foreach (Company c in list_of_companies)
{
CBItem item = new CBItem();
item.Name = c.Name;
item.Value = c.Id;
comboBox1.Items.Add(item);
}
}
問題是,當我想獲取所選項目的價值時,我已經嘗試過以下方法:
new_person.Company.Id = (comboBox1.SelectedItem).Value;
當然,它不起作用:/有任何提示嗎?
您是對的,此行有問題: new_person.Company.Id
我不知道這是什么問題。 我有模型人,該人具有公司ID的外鍵。 也許我的數據庫模型出了點問題。 我的人模型:
public class Person
{
public Person()
{
}
public int PersonId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Job { get; set; }
public int Phone { get; set; }
public int Mobile { get; set; }
public Company Company { get; set; }
}
公司型號:
public class Company
{
public Company()
{
}
public int Id { get; set; }
public string Name { get; set; }
public int NIP { get; set; }
public string Address { get; set; }
public string City { get; set; }
public int Code { get; set; }
public int Phone { get; set; }
public string Notes { get; set; }
public ICollection<Person> Person { get; set; }
}
保存代碼:
using (var db = new DataContext())
{
Person new_person = new Person();
new_person.Name = textBox1.Text;
new_person.Surname = textBox2.Text;
new_person.Job = textBox3.Text;
new_person.Phone = Int32.Parse(textBox4.Text);
new_person.Mobile = Int32.Parse(textBox5.Text);
new_person.Company.Id = (comboBox1.SelectedItem as CBItem).Value;
db.Person.Add(new_person);
db.SaveChanges();
MessageBox.Show("Person successfully added!");
this.Close();
}
您的代碼在以下情況下可以正常工作:
new_person
不為null
new_person.Company
不為null
combobox.SelectedItem
不為null
另外,您還必須像這樣將combobox.SelectedItem
CBItem
為CBItem
:
new_person.Company.Id = ((CBItem)comboBox1.SelectedItem).Value;
作為站點注釋,您可以通過將ComboBox的DataSource
屬性綁定到實現IList接口或Array的對象上,而不是一個個地添加每個項目:
comboBox1.DataSource = list_of_companies
.Select(c => new CBItem {
Name = c.Name,
Value = c.Id
})
.ToArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.