我有这个C#代码,我使用的是Sqlite
private void Form1_Load(object sender, EventArgs e)
{
using (var db = new mainEntities())
{
comboBox1.DataSource = db.Employers.ToList();
comboBox1.DisplayMember = "Surname";
comboBox1.ValueMember = "ID";
//convert to long
long id = Convert.ToInt64(comboBox1.SelectedValue);
//get employer's ID
var employer = (from s in db.Employers
where s.ID == id
select s).FirstOrDefault();
//set 2 textboxes to Name and Surname values
TextBox1.Text = employer.Name;
TextBox2.Text = employer.Surname;
db.SaveChanges();
}
}
当我尝试设置我的2个文本框时,使用以下代码更改我的组合框的值:
private void comboBox1_TextChanged(object sender, EventArgs e)
{
long id = Convert.ToInt64(comboBox1.SelectedValue);
using (var db = new mainEntities())
{
var employer = (from s in db.Employers
where s.ID == id
select s).FirstOrDefault();
//set 2 textboxes to Name and Surname values
TextBox1.Text = employer.Name;
TextBox2.Text = employer.Surname;
}
我得到: System.InvalidCastException:' System.Data.Entity.DynamicProxies.Employers_4603A50E3C8B2711C02C0DAE379C7EC403103DB450E8CCC08E7874FDC1318E90'类型' System.IConvertible'。'
如果我用此禁用代理创建:
this.Configuration.ProxyCreationEnabled = false;
在我的Db.context.cs中我得到: System.InvalidCastException:'无法对类型为&#; Db.Employers'的对象执行强制转换。类型' System.IConvertible'。'
如果我尝试转换为String而不是long并将字符串放入消息框中,我会得到2次' Db.Employers'从第三个开始,ID的数值就像在我的组合框中一样。 我哪里错了?
答案 0 :(得分:0)
private void Form1_Load(object sender, EventArgs e)
{
using (var db = new mainEntities())
{
comboBox1.DataSource = db.Employers.ToList();
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Surname";
comboBox1.SelectedIndex =0;
//convert to long
long id = Convert.ToInt64(comboBox1.SelectedValue);
//get employer's ID
var employer = (from s in db.Employers
where s.ID == id
select s).FirstOrDefault();
//set 2 textboxes to Name and Surname values
TextBox1.Text = employer.Name;
TextBox2.Text = employer.Surname;
//db.SaveChanges();
}
}
如果要更改文本值以与comboBox中的选定值相关联,可以通过SelectedIndexChanged事件
来实现private void ComboBox1_SelectedIndexChanged(object sender,System.EventArgs e)
{
long id = Convert.ToInt64(comboBox1.SelectedValue);
using (var db = new mainEntities())
{
var employer = (from s in db.Employers
where s.ID == id
select s).FirstOrDefault();
//set 2 textboxes to Name and Surname values
TextBox1.Text = employer.Name;
TextBox2.Text = employer.Surname;
}
}