[英]Getting data from selected row in DataGridView, C# WinForms
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.在 SaveChanges。 I'm trying to send it into database, but i know how to do it, i just can't get it from DataGridView.
我正在尝试将其发送到数据库中,但我知道该怎么做,只是无法从 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.