I am new to C#. I have a form with two text fields and a button and a data grid view. I am trying to pass data to Business Logic layer (BLL) and from there to Data logic layer (DAL) and there I am adding it to a list and returning back the list to the form and displaying on the data grid view. Problem is that every time I add a new record, previous records disappear. Looks like the previous entry in the list is overwritten. I have checked with debug that count in the list stays at 1. Thanks
Here is how I am calling BLL method from form to display on Data Grid:
BLL_Customer bc = new BLL_Customer();
dgvCustomer.DataSource = bc.BLL_Record_Customer(cust);
Here is the class in the 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
}
}
}
and here is the class in 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;
}
}
}
You are creating the class instances each time when try to add a new record.Make sure that only one instance of the classes are present inside any class.Create the instance of the class outside the function.
BLL_Customer bc = new BLL_Customer();
DAL_Customer dcust = new DAL_Customer();
Here's what's happening:
BLL_Customer bd = new BLL_Customer(); // Lets call this BLL_Customer #1
dgvCustomer.DataSource = bc.BLL_Record_Customer(cust); // Does what you expect
When this code is called again:
BLL_Customer bd = new BLL_Customer(); // Lets call this BLL_Customer #2
The old list and customer information is stored in BLL_Customer #1. The reference bd
no longer points to #1, but to #2. To explain this with code I can clarify like this:
var bd = new BLL_Customer().BLL_Record_Customer(cust); // A List<Customer>
bd = new BLL_Customer().BLL_Record_Customer(cust); // A new List<Customer>
Side note: Every time the class DAL_Customer
is used for the first time in an application, your List<Customer>
is initialized to a new value - in your case new List<Customer>()
.
If you do not persist the information about Customers
somehow, be it to a file, database, or some other means, every time you load your application, you'll have a new List<Customer>
to contend with.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.