Reputation: 168
I have been trying to pass a DataTable
back to the calling method. Here is the code that calls the Class
to create the DataTable
.
string SQL = "SELECT .....";
Tables.Create_DataTable(SQL);
Here is the code for the class Tables
.
public static class Tables
{
internal static object Create_DataTable(string SQL)
{
DataTable dataTable = new DataTable("Work_Orders");
using (DataAccessClass.sql_Connection)
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(SQL, DataAccessClass.sql_Connection))
{
DataAccessClass.OpenConnection();
sqlDataAdapter.Fill(dataTable);
}
return Work_Orders;
}
}
Right after the sqlDataAdapter.Fill(dataTable);
there is a Work_Orders DataTable
containing the requested data. On the return, I realize that the DataTable
is actually an object
. This is where I get stuck. How do I change the object
to a DataTable
? Then I will add it to the DataSet
.
Upvotes: 0
Views: 1946
Reputation: 3844
You should return dataTable
from your method, but as the basic question the signature should be :
attributes modifiers return-type method-name(parameters )
{
statements
}
But change your method like:
internal static DataTable Create_DataTable(string SQL)
{
DataTable dataTable = new DataTable("Work_Orders");
using (DataAccessClass.sql_Connection)
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(SQL, DataAccessClass.sql_Connection))
{
DataAccessClass.OpenConnection();
sqlDataAdapter.Fill(dataTable);
}
return dataTable;
}
EDIT:
1- Avoid to return Object from a method
2- Avoid returning DataTable from a method also
because both of them make your code unreadable and unclean, so this is better to return an object which specified for example suppose your DataTable have some fileds about user then this better to be like:
if DataTable have one row:
internal static User Create_DataTable(string SQL)
{
DataTable dataTable = new DataTable("Work_Orders");
using (DataAccessClass.sql_Connection)
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(SQL, DataAccessClass.sql_Connection))
{
DataAccessClass.OpenConnection();
sqlDataAdapter.Fill(dataTable);
}
User u = new User()
{
Name = dataTable.Rows[0]("Name"),
Family = dataTable.Rows[0]("Family"),
UserName = dataTable.Rows[0]("UserName")
}
return u;
}
or if DataTable have infos about several users (Have some rows):
internal static List<User> Create_DataTable(string SQL)
{
DataTable dataTable = new DataTable("Work_Orders");
using (DataAccessClass.sql_Connection)
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(SQL, DataAccessClass.sql_Connection))
{
DataAccessClass.OpenConnection();
sqlDataAdapter.Fill(dataTable);
}
List<User> uList = new List<User>();
foreach (DataRow row in Datatable.Rows)
{
uList.Add(new User()
{
Name = row["Name"],
Family = row["Family"],
UserName = row["UserName"]
});
}
return uList;
}
The above code just are samples.
Upvotes: 3