An error occur while adding data to datatable using loop

Feb 9 2019 3:54 AM
While we add the data to datatable using foreach loop it will get an exception i.e., "input array is longer than the number of columns in this table".
 
Example:- 
    
     DataTable dt = new DataTable(); 
     public void GetData()
     {  
           List<Employee>  emplist = db.Employees.ToList();
           foreach(var emp in emplist)
           {
                dt.Row.Add(emp.Name,emp.Address,emp.City); //Input array is longer than the...
           }
           dataGridView.DataSource=dt; 
     }
 
     public void Form_Load(object sender,EventArgs e)
     {
          dt.Columns.Add("Name",typeof(string));
          dt.Columns.Add("Address",typeof(string));
          dt.Solumns.Add("City",typeof(string)); 
      }

Answers (4)