2017-03-08 23 views
0

我尝试运行THID代码动态地添加列 - 错误

workersDVG.Columns.Add("WORKER", "worker"); 
DataGridViewRow row = (DataGridViewRow)workersDVG.Rows[0].Clone(); 
row.Cells["WORKER"].Value = 4; 
workersDVG.Rows.Add(row); 

,但我得到exeption因为没有列名“工人”。 如果有人能告诉我问题在哪里,我会很高兴。 tnx。

+0

WPF或winforms? –

+0

winforms。 TNX! –

+0

对不起,帮不了你。在过去的7年里,没有和winforms一起工作过。 –

回答

0

Clone()将无法​​工作,因为克隆的行不包含列Worker。 尝试这样的:

workersDVG.Columns.Add("WORKER", "worker"); 
//add copy of first row (index 0) 
int index = workersDVG.Rows.AddCopy(0); 
//in var index you will find index of your newly added row. 
//now add value of WORKER column in that new row 
workersDVG.Rows[index].Cells["WORKER"].Value = 4; 
+0

作品!谢谢尼诺! –

0

如果你考虑的DataGridViewRow的文档,你可以找物业DataGridView其中:

获取与此元素

如果相关的DataGridView控件在调试器中调查一下,你会发现它是null

enter image description here

因此,row找不到任何列! 另外它的索引为-1,因为它在DataGridView之外。

为什么不简单地添加下面的行并直接更改值?!这工作:

workersDVG.Columns.Add("WORKER", "worker"); 
DataGridViewRow row = (DataGridViewRow)workersDVG.Rows[0].Clone();  
workersDVG.Rows.Add(row); 
workersDVG.Rows[1].Cells["WORKER"].Value = 4;