无法以编程方式将行添加到datagrid

时间:2017-06-18 05:20:17

标签: c#

如何解决此错误:

  

当控件受数据绑定时,无法以编程方式将行添加到DataGridView的行集合中。

从以下代码:

  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;

1 个答案:

答案 0 :(得分: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);