2017-03-08 59 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;