C# 如何手添加DataGridViewRow到DataGridView
- C# code
SortableBindingList<ImportUseableInfo> models = item.GetUseableBargainByCIQPN(ciqpn);//取集 //this.dataGridView1.DataSource = item.GetUseableBargainByCIQPN(ciqpn); foreach (ImportUseableInfo model in models) { DataGridViewRow dr = new DataGridViewRow(); dr.Cells["BargainNO"].Value = model.BargainNO; dr.Cells["SeqID"].Value = model.SeqID; dr.Cells["CIQPN"].Value = model.CIQPN; dr.Cells["CIQCode"].Value = model.CIQCode; dr.Tag=model.UseQty; this.dataGridView1.Rows.Add(dr); }
DataGridView在界面中已置了列,可行是出,提示找不到列"BargainNO"。!
[解决办法]
DataGridViewRow dr = new DataGridViewRow();
dr.Cells["BargainNO"].Value = model.BargainNO;
==========
DataGridView在界面中已置了列
如果已有一个DataGridView实体,这儿应该设置此实体对象,而不是设置一个新的 DataGridViewRow
更可能的方法应该是
DataGridViewRow1.Cells...............................
如果有一个DataGridView子类,则应为
MyDataGridView dr=new MyDataGridView();
dr.cells........................
[解决办法]
你这样当然出错了,你看你代码的思路:新建行-->给行的列赋值-->把行加入网格
你在给行的列赋值的时候,该行是空的,尚没有列.所以得先给行添加列:
- C# code
foreach (ImportUseableInfo model in models) { DataGridViewRow dr = new DataGridViewRow();foreach(DataGridViewCell c in dataGridView1.Columns){dr.Cells.Add(c.CellTemplate.Clone() as DataGridViewCell);//给行添加单元格} dr.Cells["BargainNO"].Value = model.BargainNO; dr.Cells["SeqID"].Value = model.SeqID; dr.Cells["CIQPN"].Value = model.CIQPN; dr.Cells["CIQCode"].Value = model.CIQCode; dr.Tag=model.UseQty; this.dataGridView1.Rows.Add(dr); }