12,448,059 members (85,828 online)

Email

Password

Sign in using

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?

```
foreach (DataRow dr in datatable.Rows)
{
datagridview.Rows.Add(dr);
}
```

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.

DataRow[] rows = ds.Table["tablename"].Select("columnA='"+textbox1.Text+"'");

if (rows.Length > 0) dataGridView1.DataSource = rows.CopyToDataTable();

if (rows.Length > 0) dataGridView1.DataSource = rows.CopyToDataTable();

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.

I tried it this way and it is working:

```
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;
```

Comments

And how is not making use of databinding? The OP stated he does not want to use it.

dr["A"] = (i + 1).ToString();

dr["B"] = (i + 1).ToString();

dr["C"] = (i + 1).ToString();

dt.Rows.Add(dr);

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.

not be entirely correct.

```
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;
```

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

CodeProject,
503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada
+1 416-849-8900 x 100