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 を呼び出した後、最初の 2 行以外のすべての行が消えることです ( grid.Rows.Count が 2 になります)。最初の行はデータを保持し、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 プロパティを Customer を指すように設定します)。このコードは、私が上に投稿したコードと非常によく似ています。customerBindingSource.List を反復処理し、ID の値に基づいて呼び出す正しいメソッドを決定します。最初の要素で AddCustomer または EditCustomer を呼び出すと、リストの他のすべての要素が空中に消えてしまいます。

4

0 に答える 0