Click here to Skip to main content
16,015,393 members
Please Sign up or sign in to vote.
2.25/5 (4 votes)
See more:
I'm trying to insert data rows from a datatable into a datagridview. I don't want to bind the datatable to the datagridview for reasons I won't bore you with right now. I don't want to iterate through each row and column to insert values because that's take a long time. The datatable and datagridview have the same columns, but the number of columns can change depeding on options selected by the user.

Seems simple. But I can't get it to work. I've posted some psuedo-code below. Can I somehow cast a datarow to a datagridview row?

Any ideas?

C#
foreach (DataRow dr in datatable.Rows)
{
   datagridview.Rows.Add(dr);
}
Posted
Updated 23-May-11 17:27pm
v2

You simply have no choice. You have to do one or the other of the things you said you don't want to do. You cannot cast a datarow to a datagridviewrow. It's just not possible because there is no conversion between the two.
 
Share this answer
 
DataRow[] rows = ds.Table["tablename"].Select("columnA='"+textbox1.Text+"'");
if (rows.Length > 0) dataGridView1.DataSource = rows.CopyToDataTable();
 
Share this answer
 
Well if you don't want to use data binding nor want to add rows manually then there isn't much you can do except give up and let someone else do it the correct way.
 
Share this answer
 
I tried it this way and it is working:

C#
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("A");
dt.Columns.Add("B");
dt.Columns.Add("C");
for (int i = 0; i < 10; i++)
{
    dr = dt.NewRow();

    dr["A"] = "A" + (i + 1).ToString();
    dr["B"] = "B" + (i + 1).ToString();
    dr["C"] = "C" + (i + 1).ToString();
    dt.Rows.Add(dr);
}
dataGridView1.DataSource = dt;
 
Share this answer
 
Comments
[no name] 25-May-11 16:02pm    
And how is not making use of databinding? The OP stated he does not want to use it.
krushna chandra jena 4-Apr-13 2:34am    
dr["A"] = (i + 1).ToString();
dr["B"] = (i + 1).ToString();
dr["C"] = (i + 1).ToString();
dt.Rows.Add(dr);
I think solution 3 might be done a little easier by using your idea with a little modification. Please note that I am more familiar with VB.Net so the code may
not be entirely correct.
C#
DataTable dt = new DataTable();
dt.Columns.Add("A");
dt.Columns.Add("B");
dt.Columns.Add("C");

foreach (DataRow dr in datatable.Rows)
  {
    dr = dt.NewRow();
    dr["A"] = "A" + (i + 1).ToString();
    dr["B"] = "B" + (i + 1).ToString();
    dr["C"] = "C" + (i + 1).ToString();
    dt.Rows.Add(dr);
  }


 dataGridView1.DataSource = dt;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900