当控件是数据绑定时,无法以编程方式将行添加到DataGridView的行集合中。 [英] Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.

查看:1819
本文介绍了当控件是数据绑定时,无法以编程方式将行添加到DataGridView的行集合中。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



我使用此代码使用datatable在datagridview中显示项目。但它显示错误: -

当控件受数据绑定时,无法以编程方式将行添加到DataGridView的行集合中。



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.

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;



请帮帮我。



先谢谢。





Ankit Agarwal

软件工程师



[edit]在\\之后添加空格,以避免转义引号和代码格式的混乱[/ edit]


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]

推荐答案

您好,它不是直接向Datagrid添加行的正确方法....尝试向dataSource(Datatable或Dataset)添加一行,然后尝试将DataTable绑定到该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":
dgvDisplayTiles.ItemSourc=DataTable;(DataTable is source)





然后向DataTable添加一行并将源提供给网格视图。 ..



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


简单地说你根本不需要这样做,设置DataSource应该填充网格。



如果要实现自定义逻辑在生成列值时,您应该隐藏实现IBindingSource的转换器后面的DataTable并公开相应的列。
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.


这篇关于当控件是数据绑定时,无法以编程方式将行添加到DataGridView的行集合中。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆