0

SqlDataReader、DataGridView、および List の 3 つのパラメーターを使用できる関数を作成しようとしています。

SqlDataReader の内容を取得してオブジェクトのリストを作成し、これを DataGridView にバインドします。

別のスタックオーバーフローユーザーからのいくつかのポインタを使用して、次のことを思いつきました。

public void FillArrayList<T>(DataGridView grid, SqlDataReader reader, List<T> list)
{
    //Fill the list with the contents of the reader
    while (reader.Read())
    {
        Object obj = new Object();
        Type type = typeof(T);

        FieldInfo[] fields = type.GetFields(); // Get the fields of the assembly
        int i = 0;

        foreach(var field in fields)
        {
            field.SetValue(obj, reader[i]); // set the fields of T to the reader's value
            i++;
        }

        list.Add((T)obj);
    }

    grid.DataSource = list;
}

コードを実行すると、オブジェクトを T 型にキャストするときにエラーが発生します。

タイプ「System.Object」のオブジェクトをタイプ「TestHarness.Organisation」にキャストできません。

オブジェクトには何でも保存できるという印象を受けました。このキャストを実行できない理由について誰か教えてもらえますか?

ありがとう、

アンディ

4

2 に答える 2

2

ほとんど何でもオブジェクトにキャストできますが、オブジェクトを何かにキャストすることはできません。MSDN のSystem.Objectクラスを見てください。そこにはほとんど何もないことに注意してください。新しい TestHarness.Organization を呼び出すのと機能的に同じであるため、キャストは意味がありません。

TestHarness.Organization またはそれが何であれ、 DataReader で探しているものが正確にわかっている場合は、ユーザー定義の変換を試すことができます。これにより、暗黙的または明示的に何らかのコードを呼び出して、その場で追加のコードを使用せずに型の変更を行うことができます。

于 2012-06-11T19:30:24.610 に答える
0

私の質問の下のコメントで、MMK によって投稿されたリンクから少し助けて、解決策を考案しました。

public void FillList<T>(DataGridView grid, string SQLCommand, List<T> list) where T : class, new()
    {
        //Load the data into the SqlDataReader
        SqlCommand dataCommand = new SqlCommand();
        dataCommand.Connection = dataConnection;
        dataCommand.CommandType = CommandType.Text;
        dataCommand.CommandText = SQLCommand;

        SqlDataReader dataReader = dataCommand.ExecuteReader();

        //Fill the list with the contents of the reader
        while (dataReader.Read())
        {
            var obj = new T();

            //Get the property information
            PropertyInfo[] properties = typeof(T).GetProperties();
            int i = 0;

            foreach(var property in properties)
            {
                property.SetValue((T)obj, dataReader[i], null); // set the fields of T to the reader's value
                i++;
            }

            list.Add(obj);
        }

        dataReader.Close();

        //Bind the list to the DataGridView
        grid.DataSource = list;
    }

私が必要とすることを正確に行うようです。これをますます多くの状況で使用するにつれて、明らかなエラーに遭遇する可能性がありますが、これは人生です.

助けてくれてありがとう、みんな!

于 2012-06-22T18:57:32.520 に答える