日期:2014-05-18  浏览次数:20918 次

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);
            }