Click here to Skip to main content
15,881,753 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I am using this code for display items in datagridview using datatable. but it's showing error:-
Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.

C#
for (int i = 0; i < dt.Rows.Count; i++)
           {
               dgvDisplayTiles.Rows.Add();
               dgvDisplayTiles.Rows[i].Cells[0].Value = dt.Rows[i][0].ToString();
               dgvDisplayTiles.Rows[i].Cells[1].Value = dt.Rows[i][1].ToString();
               dgvDisplayTiles.Rows[i].Cells[2].Value = dt.Rows[i][2].ToString();

               Bitmap img = new Bitmap(Application.StartupPath + "\\ " + dt.Rows[i][3].ToString());
               dgvDisplayTiles.Rows[i].Cells[3].Value = img;

               try
               {
                   Bitmap img3 = new Bitmap(Application.StartupPath + "\\ " + dt.Rows[i][4].ToString());
                   dgvDisplayTiles.Rows[i].Cells[4].Value = img3;
               }
               catch (Exception ex)
               {
                   Bitmap img3 = new Bitmap(Application.StartupPath + "\\Library\\NoTiles.png");
                   dgvDisplayTiles.Rows[i].Cells[4].Value = img3;
               }

           }
           dgvDisplayTiles.AutoGenerateColumns = false;
           dgvDisplayTiles.DataSource = dt;

Please help me.

Thanks in Advance.


Ankit Agarwal
Software Engineer

[edit]Empty Space added after \\ to avoid escaped quotes and the mess of code format[/edit]
Posted
Updated 10-Dec-13 23:33pm
v4
Comments
jing567 11-Dec-13 3:34am    
Hello,
Its not right way to add a row to directly to Datagrid.... Try adding a row to the dataSource(Datatable or Dataset) and then try to bind the DataTable to that Grid View...


For Example":
dgvDisplayTiles.ItemSourc=DataTable;(DataTable is source)

Then Add a Row to the DataTable and the give the source to the Grid view...

Hello, Its not right way to add a row to directly to Datagrid.... Try adding a row to the dataSource(Datatable or Dataset) and then try to bind the DataTable to that Grid View...

For Example":
C#
dgvDisplayTiles.ItemSourc=DataTable;(DataTable is source)


Then Add a Row to the DataTable and the give the source to the Grid view...
 
Share this answer
 
v3
Simply put you don't need to do this at all, setting the DataSource should populate the grid.

If you want to implement custom logic in generating the column values, you should hide the DataTable behind a converter which implements IBindingSource and exposes the appropriate columns.
 
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