Hi buddies
well say i have table with data .. i want to copy the same data to other table ..
PS : Here copy() should not be used .. Well i know there is a way to achieve this i.e using clone and later Rows.add() ..
But I NEED IS , CAN ANYONE correct the stupid code i written i.e data copying b/w tables via datasetsusing forLoop ?/
My code so far :
private void Form1_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=sunil-pc;Initial Catalog=formdb;User ID=sa;Password=123");
SqlCommand cmd = new SqlCommand("select * from formtable", con);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds, "table1");
dataGridView1.DataSource = ds.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
DataSet ds1 = new DataSet();
int columns = ds.Tables[0].Columns.Count;
int rows = ds.Tables[0].Rows.Count;
for (int i = 0; i < rows; i++)
{
for (int j = 1; j < columns + 1; j++)
{
ds1.Tables[0].Rows[i][j] = ds.Tables[0].Rows[i][j];
}
}
dataGridView2.DataSource = ds1.Tables[0];
}
Well i hope i am clear :) Ty for help
Have a nice day :)

Jignesh TrivediPosted Dec 23, 2013, 3:29 AM
hi,
Try this code in button click event
DataSet ds1 = new DataSet();
int columns = ds.Tables[0].Columns.Count-1;
int rows = ds.Tables[0].Rows.Count;
// create New dataTable and column of data table
DataTable dt = new DataTable();
foreach(DataColumn col in ds.Tables[0].Columns)
{
dt.Columns.Add(col.ColumnName, col.DataType);
}
// add table in to data set
ds1.Tables.Add(dt);
// copy the data...
foreach (DataRow drow in ds.Tables[0].Rows)
{
DataRow dRowAdd = ds1.Tables[0].NewRow();
for (int k = 0; k <= columns; k++)
{
dRowAdd[k] = drow[k];
}
ds1.Tables[0].Rows.Add(dRowAdd);
}
hope this will help you.
SUNIL GUTTAPosted Dec 23, 2013, 4:49 AM
That was brilliant technique :) cheers .. adding columns initially , later doing with rows nice trick :)
Ty very much
SUNIL GUTTAPosted Dec 23, 2013, 3:18 AM
Ty for concerned reply .
Well no issues it can be done with copy or else with other method i.e using clone..
Just i am just interested to know.. can this be done using above mentioned way .. i.e transfer of data i.e rows & columns b/w datasets (collection if dt's)
Cheers
Ty
Jaganathan BantheswaranPosted Dec 23, 2013, 2:02 AM
What is the issue if you use Copy() method?