我是EF的新手,并尝试使用ADO.NET EF在组合框更改事件上填充文本框上的数据。我尝试解析所有内容,但错误始终存在。我的代码如下...... 请帮助我....提前致谢。
private List<tSubDepartment> GetSubDepartmentInfo(int deptId)
{
using (DiagnosoftDataContext context = new DiagnosoftDataContext())
{
return (from c in context.tSubDepartments
where c.dpCode == deptId
select c).ToList();
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var subDeptInfo =GetDepartmentInfo((int)comboBox1.SelectedValue); // Error: "Specific cast is not valid"
textBox2.Text = subDeptInfo[0].sdCode.ToString();
textBox3.Text = subDeptInfo[0].sdName;
textBox4.Text = subDeptInfo[0].dpCode.ToString();
}
这是我填充组合框的代码
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.DataSource = GetSubDepartments();
comboBox1.DisplayMember = "sdName";
comboBox1.ValueMember = "sdCode";
}
private List<tSubDepartment> GetSubDepartments()
{
using (DiagnosoftDataContext context = new DiagnosoftDataContext())
{
return (from c in context.tSubDepartments select c).ToList();
}
}
答案 0 :(得分:0)
看起来它与EF无关。我的猜测是你的组合框中的值是字符串,而不是整数。所以你可以尝试
int.Parse(comboBox1.SelectedValue)
而不是
(int)comboBox1.SelectedValue
如果这不起作用,那么你可能还有其他东西 - 看一下comboBox1.SelectedValue
是什么类型的对象 - 它可以是任何东西。这就是你需要把它投射到那里,然后从那里使用对象。
答案 1 :(得分:0)
试试这个,
if (comboBox1.SelectedItem != null)
{
int x = int.Parse(comboBox1.SelectedItem.ToString());
var subDeptInfo =GetDepartmentInfo(x);
textBox2.Text = subDeptInfo[0].sdCode.ToString();
textBox3.Text = subDeptInfo[0].sdName;
textBox4.Text = subDeptInfo[0].dpCode.ToString();
}
else { //Value is null }