1

I am trying to execute a stored procedure with parameters, and get the results into a DataTable; but after execution, I get this:

this is the screen

I can get IDataRecord but I can't IDataReader - why? What do I miss? Thanks

public DataTable ExecuteProcedureTest(string storedProcedure, Dictionary<Filter, object> filterValue)
{
    var parameters = GetParams(filterValue);

    var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["testconn"].ConnectionString);

    var cmd = sqlConnection.CreateCommand(); 

    SqlDataReader reader;
    IDataReader dataReader;
    IDataRecord[] dataRecords;

    var table = new DataTable();

    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = storedProcedure;

    foreach (var item in parameters)
    {
        cmd.Parameters.Add(item);
    }

    try
    {
        sqlConnection.Open();
        reader = cmd.ExecuteReader();

        dataRecords = reader.OfType<IDataRecord>().ToArray();
        table.Load(reader);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        sqlConnection.Dispose();
    }

    //var count = dataRecords.Count();
    return table;
} 
2
  • This call dataRecords = reader.OfType<IDataRecord>().ToArray(); read all records. There is nothing left in the reader for table.Load(reader); to work with. Commented Dec 25, 2017 at 14:39
  • So that is example when i try everything what i know. So is the same result when i remove that line of code. And please stop giving negative point before then user answer on your comment :S :S Commented Dec 25, 2017 at 14:50

1 Answer 1

1

If your goal is to fill a DataTable from a SqlCommand, use a SqlDataAdapter instead of a SqlDataReader. Here is a handy extension method:

public static class SqlExtensions
{
    public static DataTable ExecuteDataTable(this SqlCommand command)
    {
        DataTable table = new DataTable();
        using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
        {
            dataAdapter.Fill(table);
        }
        return table;
    }
}

Then from your code you can use it like this:

try
{
    sqlConnection.Open();
    table = cmd.ExecuteDataTable();
}
finally
{
    sqlConnection.Dispose();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.