DataGridView行消失没有明显的原因

时间:2012-08-01 13:00:37

标签: c# datagridview

我正在使用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;
}

这是Customer的构造函数:

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属性设置为指向Customer)。代码与我上面发布的代码非常相似;迭代customerBindingSource.List并根据ID的值确定要调用的正确方法。问题仍然存在,在第一个元素上调用AddCustomer或EditCustomer会使列表中的所有其他元素消失得无影无踪。

0 个答案:

没有答案