Say I have a database with 2 tables with the following names (tbl1 and tbl2).
Each of the table above have different number of columns, tbl1 has 3 while tbl2 has 4 columns.
I need to copy each of the above tables in a DataTable.
Of course I can do it manually like the following codes below:
class
{
public Main()
{
// for tbl1 with 3 columns.
string sql = "select * from tbl1"
MySqlCommand com = new MySqlCommand(sql, con);
MySqlDataReader dr = com.ExecuteDataReader();
DataTable dt = GetDataTable(3);
while (dr.Read())
{
if (dr.HasRows)
{
dt.Rows.Add(dr[0], dr[1], dr[2]); <---- Point of interest
}
}
// for tbl2 with 4 columns.
string sql = "select * from tbl2";
MySqlCommand com = new MySqlCommand(sql, con);
MySqlDataReader dr = com.ExecuteDataReader();
DataTable dt = GetDataTable(4);
while (dr.Read())
{
if (dr.HasRows)
{
dt.Rows.Add(dr[0], dr[1], dr[2], dr[3]); <---- Point of interest
}
}
}
public DataTable GetDataTable(int columnCount)
{
DataTable dt = new DataTable();
if (columnCount > 0)
{
for (int i = 0; i < length; i++)
{
dt.Columns.Add(i.ToString(), typeof(object));
}
}
return dt;
}
}
But what I would like to do is to make the process above in an automated way, especially on the part where I indicated an arrow.
Is there a way I could dynamically add rows like what I did on the columns?
I was thinking I could add rows dynamically by using a function that generates the process of adding rows as string and call that string as a command but I am really really lost and don't know what to do... pls see the code below.
EX:
String generated from a function base on number of columns:
"dt.Rows.Add(dr[0], dr[1], dr[2], dr[3])"
Then, use the string as a command to add rows...
Fillmethod on the DataTable.