0

私はC#が初めてです。2 つのテキスト フィールドとボタン、およびデータ グリッド ビューを含むフォームがあります。データをビジネス ロジック レイヤー (BLL) に渡し、そこからデータ ロジック レイヤー (DAL) に渡そうとしています。リストに追加し、リストをフォームに戻し、データ グリッド ビューに表示しています。問題は、新しいレコードを追加するたびに、以前のレコードが消えることです。リストの前のエントリが上書きされているようです。リスト内のカウントが1のままであることをデバッグで確認しました。ありがとう

フォームから BLL メソッドを呼び出してデータ グリッドに表示する方法は次のとおりです。

   BLL_Customer bc = new BLL_Customer();
   dgvCustomer.DataSource = bc.BLL_Record_Customer(cust);

これがBLLのクラスです

 namespace BLL
 {
     public class BLL_Customer
     {

         public List<Customer> BLL_Record_Customer(Customer cr)
         {
             DAL_Customer dcust = new DAL_Customer();
             List<Customer> clist = dcust.DAL_Record_Customer(cr); 
             return clist;  // Reurning List
         }
     }

 }

DALのクラスは次のとおりです。

namespace DAL
 {

     public class DAL_Customer

     {
         List<Customer> clist = new List<Customer>();
         public List<Customer> DAL_Record_Customer(Customer cr)
         {
             clist.Add(cr);
             return clist;
         }
     }
 }
4

2 に答える 2

0

何が起こっているかは次のとおりです。

BLL_Customer bd = new BLL_Customer(); // Lets call this BLL_Customer #1
dgvCustomer.DataSource = bc.BLL_Record_Customer(cust); // Does what you expect

このコードが再度呼び出されると、次のようになります。

BLL_Customer bd = new BLL_Customer(); // Lets call this BLL_Customer #2

古いリストと顧客情報は、BLL_Customer #1 に保存されます。参照bdはもはや #1 ではなく #2 を指しています。これをコードで説明するには、次のように明確にします。

var bd = new BLL_Customer().BLL_Record_Customer(cust); // A List<Customer> 
bd = new BLL_Customer().BLL_Record_Customer(cust); // A new List<Customer>

補足: クラスDAL_Customerがアプリケーションで初めて使用されるたびにList<Customer>、あなたの場合は新しい値に初期化されますnew List<Customer>()

ファイル、データベース、またはその他の手段で情報を永続化しない場合Customers、アプリケーションをロードするたびに新しい問題が発生List<Customer>します。

于 2013-09-02T00:34:35.607 に答える