1

我正在使用 DataGridView 添加、编辑和查看数据。当用户按下按钮时,我想保存他所做的所有编辑。在运行时根据只读单元格值做出决定,以确定是否需要添加或编辑当前记录。所以这里是代码:

int bad = 0;
foreach ( DataGridViewRow row in grid.Rows ) {
    if ( IsValidRow( row ) ) {
        row.Cells[ "colStatus" ].Value = bmpTick;

        string id = ( string ) row.Cells[ "colID" ].Value;
        if ( id != null ) {
            customerManager.EditCustomer( new Guid( id ),
                newFirstName: ( string ) row.Cells[ "colFirstName" ].Value,
                newSecondName: ( string ) row.Cells[ "colSecondName" ].Value,
                newPhone: ( string ) row.Cells[ "colPhone" ].Value,
                newResidence: ( string ) row.Cells[ "colResidence" ].Value );
        }
        else {
            customerManager.AddCustomer(
                firstName: ( string ) row.Cells[ "colFirstName" ].Value,
                secondName: ( string ) row.Cells[ "colSecondName" ].Value,
                phone: ( string ) row.Cells[ "colPhone" ].Value,
                residence: ( string ) row.Cells[ "colResidence" ].Value );
        }
    }
    else bad += 1;
}

问题是在调用 AddCustomer 或 EditCustomer 之后,所有行,但前两行消失( grid.Rows.Count 变为 2 )。第一行保留其数据,而第二行所有单元格都为空。这里是 AddCustomer 和 RemoveCustomer:

private List<Customer> _customers;

// ...

public void AddCustomer( 
    string firstName, 
    string secondName,
    string residence,
    string phone )
{
    Customer toAdd = new Customer( firstName, secondName, residence, phone );
    toAdd.CustomerEdited += this.CustomerEdited;

    _customers.Add( toAdd );
    _customers.Sort( );

    OnCustomerAdded( toAdd );
}

public void EditCustomer(
    Guid id,
    string newFirstName = "",
    string newSecondName = "",
    string newPhone = "",
    string newResidence = "" )
{

    Customer cus = _customers.Single( c => c.ID == id );

    if ( newFirstName != string.Empty ) cus.FirstName = newFirstName;
    if ( newSecondName != string.Empty ) cus.SecondName = newSecondName;
    if ( newPhone != string.Empty ) cus.Phone = newPhone;
    if ( newResidence != string.Empty ) cus.Residence = newResidence;
}

这是客户的构造函数:

public Customer( 
    string firstName,
    string secondName,
    string residence,
    string phone )
{
    this._firstName = firstName;
    this._secondName = secondName;
    this._residence = residence;
    this._phone = phone;

    this.ID = Guid.NewGuid( );
}

如您所见,我从不编辑从单元格中检索到的值,所以我真的不明白为什么表格会被破坏。

编辑:
我遵循了 DavidHall 在其评论中给出的建议(将 DataGridView 的 DataSource 属性设置为指向客户)。该代码与我上面发布的代码非常相似;遍历 customerBindingSource.List 并根据 ID 的值确定要调用的正确方法。但是问题仍然存在,在第一个元素上调用 AddCustomer 或 EditCustomer 会使列表中的所有其他元素消失得无影无踪。

4

0 回答 0