How to read whole row and save it to variable? I know what type is stored there (custom Employee type).
I have tried doing it kind of manually.
private async void AddEmployee()
{
var context = new NorthwindContext();
int selectedRowCount = EmpMgmtDataGridView.Rows.GetRowCount(DataGridViewElementStates.Selected);
if (selectedRowCount > 0)
{
for (int i = 0; i < selectedRowCount; i++)
{
var employeeToAdd = new Employees();
employeeToAdd.FirstName = EmpMgmtDataGridView[1, i].ToString();
employeeToAdd.LastName = EmpMgmtDataGridView[2, i].ToString();
await context.AddAsync(employeeToAdd);
await context.SaveChangesAsync();
}
}
}
But it ends with
SqlException: String or binary data would be truncated.
The statement has been terminated.
at SaveChanges. I'm trying to send it into database, but i know how to do it, i just can't get it from DataGridView.
Edit
Made an upgrade but it ends with identical error.
private async void AddEmployee()
{
var context = new NorthwindContext();
int selectedRowCount = EmpMgmtDataGridView.Rows.GetRowCount(DataGridViewElementStates.Selected);
var rows = EmpMgmtDataGridView.SelectedRows;
if (selectedRowCount > 0)
{
for (int i = 0; i < selectedRowCount; i++)
{
var employeeToAdd = new Employees();
employeeToAdd.LastName = rows[i].Cells[1].ToString();
employeeToAdd.FirstName = rows[i].Cells[2].ToString();
await context.AddAsync(employeeToAdd);
await context.SaveChangesAsync();
}
}
}
Make sure you are actually getting the Value of the cell rather than the cell object itself:
employeeToAdd.LastName = rows[i].Cells[1].Value.ToString();
employeeToAdd.FirstName = rows[i].Cells[2].Value.ToString();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.