I have the following code:
public static DataTable GetDataTable(string sConnStr, string sTable)
{
DataTable dt = new DataTable();
SqlConnection sqlC
Don't use a SqlDataReader
, use a SqlDataAdapter
. A DataReader
is for fast, forward-only operations, while the DataAdapter
is geared towards set-based operations.
See MSDN: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx
See http://www.dotnetperls.com/sqldataadapter for a simple example.
You could use a data adapter:
public static DataTable GetDataTable(string sConnStr, string sTable)
{
using (SqlConnection sqlConn10 = new SqlConnection(sConnStr))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM EmployeeIDs", sqlConn10))
{
sqlConn10.Open();
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
}
DataAdapter.Fill(DataTable, mySqlQuery);
http://msdn.microsoft.com/en-us/library/497b1k4t.aspx
Simply Do this:
SqlDataReader myReader10 = sqlComm10.ExecuteReader();
dt.Load(myReader10);
and return dt;
So your would be like this:
try
{
while (myReader10.Read())
{
dt.Load(myReader10);
}
}
catch
{
myReader10.Close();
sqlConn10.Close();
}
return dt;
The easiest way would be to use a DataAdapter to fill a datatable.
public static DataTable GetDataTable(string sConnStr, string sTable)
{
using (SqlConnection sqlConn10 = new SqlConnection(sConnStr))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM " + sTable, sqlConn10))
{
sqlConn10.Open();
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
}
// you should use best practices, use the using statement to dispose connection and other objects after completion of work.
public static DataTable GetDataTable(string sConnStr, string sTable)
{
DataTable dt = new DataTable();
try
{
using (SqlConnection sqlConn10 = new SqlConnection(sConnStr))
using (SqlCommand sqlComm10 = new SqlCommand("SELECT * FROM " + sTable, sqlConn10))
{
sqlConn10.Open();
using (SqlDataReader myReader10 = sqlComm10.ExecuteReader())
{
dt.Load(myReader10);
}
}
}
catch(Exception ex)
{
}
return dt;
}
Ref: Put SqlDataReader data into a DataTable while i process it