2017-06-18 86 views
0

如何解決此錯誤:行不能以編程方式添加到數據網格

Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.

從下面的代碼:

string str = "Er.fName,Er.lName"; 
     DataSet dataSet = new DataSet(); 
     DataSet info = this.GetData.getInfo("SELECT 0 AS ErNo, Er.EmpID, (Er.fName&''&sr.lName) AS [Employee Name], Ed.DeptNo AS [Dept No] FROM (EmployeeReg AS Er INNER JOIN EmployeeDept AS Ed ON Er.EmpId = Er.EmpId) WHERE Ed.DeptId=" + (object) DeptID + " AND Ed.Status=0 AND Er.EmpStatus=1 ORDER BY " + str, "EmployeeDept"); 
if (info.Tables[0].Rows.Count > 0) { 
    for (int index = 0; index < info.Tables[0].Rows.Count; ++index) 
    //error from the code blw 
    this.dgvPrint.Rows.Add((object) 0, (object)(index + 1), (object) info.Tables[0].Rows[index]["Emp Name"].ToString(), (object) info.Tables[0].Rows[index]["Emp No"].ToString(), (object) info.Tables[0].Rows[index]["EmpId"].ToString()); 
} 
if (this.dgvPrint.Rows.Count > 0) 
    this.btnPrint.Enabled = true; 
else 
    this.btnPrint.Enabled = false; 
+0

請格式化代碼爲可讀格式。 – Guy

+1

它非常明顯的錯誤。當你有綁定的數據網格你不能添加項目。 –

+0

什麼是Datagridview的數據源? –

回答

0
var table = info.Tables[0]; 
table.Rows.Add(new object[] { 
     0, 
     index + 1, 
     table.Rows[index]["Emp Name"], 
     table.Rows[index]["Emp No"], 
     table.Rows[index]["EmpId"] 
}); 

或:

var table = info.Tables[0]; 
var new = table.NewRow(); 
new["colllName"] = 1; 
new["colllName 2"] = 2; 
//ect... 
table.Rows.Add(new); 
相關問題