I am very new to EF and trying to populate data on textbox on combobox change event using ADO.NET EF. I tried parsing everything but error exists all the time. My code is given below.... Please help me....Thanks in advance.
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();
}
Here is my code to populate combobox
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();
}
}
Looks like it's got nothing to do with EF. My guess is your values in your combobox are strings, not integers. So you can try
int.Parse(comboBox1.SelectedValue)
instead of
(int)comboBox1.SelectedValue
If that doesn't work, then you've probably got something else in there - take a look at what kind of object comboBox1.SelectedValue
is - it can be anything. That's what you'd need to cast it to, then work with the object from there.
Try this,
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 }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.