1

BAL で指定されたフィールド名を持つ顧客のリストを提供する WCF サービスを呼び出しています。多くのフォーラムで指示されている方法を作成しましたToDataTable(この例では間違っている可能性があります)。リストをデータテーブルに変換するために使用しますが、直面している課題があります。エラーには、「タイプ 'System.Data.DataTable を mHotRes.DesktopPresentation.ListFrm.ListType に暗黙的に変換できません」と表示されます。

データをバインドするための私のコードは次のとおりです。

private void BindData()
    {
        try
        {
            switch (_ListType)
            {
                case ListType.Customers:
                    IHotRes res = new MHotServiceProvider().Service;
                     List<Customer> customer = res.CustomerSaveDataList();

                    _ListType = ToDataTable(customer); //the problem occurs here
                    break;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

ToDataTableメソッドのコードは次のとおりです。

public static DataTable ToDataTable<T>(List<T> items)
    {
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name);
        }
        foreach (T item in items)
        {
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
            {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
            }
            dataTable.Rows.Add(values);
        }
        //put a breakpoint here and check datatable
        return dataTable;
    }

さらにコード サンプルが必要な場合はお知らせください。

4

1 に答える 1

1

あなたのリフレクション ToDataTable コードは正しく動作しています:

_ListType = ToDataTable(customer); //the problem occurs here

問題は、 と の_ListTypeタイプが異なることDataTableです。

行を次のように変更する必要があります

DataTable tbl = ToDataTable(customer);//Your method returns DataTable
于 2016-10-18T10:32:56.973 に答える