簡體   English   中英

ADO.NET實體框架4中的轉換錯誤

[英]Casting error in ADO.NET Entity Framework 4

我對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();

        }
    }

看起來它與EF無關。 我的猜測是您在組合框中的值是字符串,而不是整數。 所以你可以嘗試

int.Parse(comboBox1.SelectedValue)

代替

(int)comboBox1.SelectedValue

如果這不起作用,那么您可能還有其他東西-看看comboBox1.SelectedValue是哪種對象-它可以是任何東西。 那就是您需要將其轉換為對象,然后從那里使用該對象的方法。

嘗試這個,

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 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM