AngelicCore
AngelicCore

Reputation: 1453

How to return a datatable from a database table, not using adapter.fill

I wish to return a Datatable not using the adapter.fill technique.

    internal DataTable ConnectedSelect(string TableName, string[] Cols, string Condition)
    {
        DataTable dt = new DataTable();
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
        {
            con.Open();
            using (SqlCommand cmd = new SqlCommand(GenerateSelectStatment(TableName, Cols, Condition),con))
            {
                SqlDataReader rdr = cmd.ExecuteReader();
                object[] temp = new object[rdr.FieldCount];
                while (rdr.Read())
                {
                   rdr.GetValues(temp);
                   dt.Rows.Add(temp);
                }
            }
        }
        return dt;
    }
    }

problem is i get Input array is longer than number of col in this table. table has 4 columns What could be the problem? the rows.add should be adding a row with 4 elements which is the same as input.

Upvotes: 1

Views: 3185

Answers (1)

syed mohsin
syed mohsin

Reputation: 2938

You can use load method of DataTable

 dt.Load(rdr);

Whole code would be

internal DataTable ConnectedSelect(string TableName, string[] Cols, string Condition)
{
    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
    {
        con.Open();
        using (SqlCommand cmd = new SqlCommand(GenerateSelectStatment(TableName, Cols, Condition),con))
        {
            SqlDataReader rdr = cmd.ExecuteReader();
            if(rdr.HasRows)
               dt.Load(rdr);
        }
    }
    return dt;
}
}

Upvotes: 2

Related Questions