Hi there I was wondering if its possible for me to create a method in my customer.cs to delete a customer depending on its ID. How I want this to work is that the user will select a customer from the list box which only shows the customers firstName and then hit delete which will delete the customer off the list box. But I want to somehow create a method in the customer.cs which will look at the ID then delete it if its the right one. Can this be done? Any help would be create thank you.
form.cs:
public partial class AddCustomer : Form
{
List<Customer> list = new List<Customer>();
Random rand = new Random();
public AddCustomer()
{
InitializeComponent();
}
// Adds Customer
private void buttonAddCustomer_Click(object sender, EventArgs e)
{
Customer customer = new Customer();
customer.customerId = rand.Next();
customer.firstName = textBoxfn.Text;
list.Add(customer);
listBoxCustomers.Items.Add(customer.firstName);
}
// Deletes Customer
private void buttonDeleteCustomer_Click(object sender, EventArgs e)
{
listBoxCustomers.Items.Remove(listBoxCustomers.SelectedItem);
}
}
}
Customer.cs:
public class Customer
{
public int customerId;
public string firstName;
public string lastName;
public string phoneNumber;
public string address;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string PhoneNumber
{
get { return phoneNumber; }
set { phoneNumber = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
}
}
One idea is to load your customer list into a BindingList<Customer>
Now with this approach you work from the BindingList and the selected index of the ListBox.
I used a pre-defined customer class I had.
public class Customer
{
public int CustomerIdentifier { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public int CountryIdentifier { get; set; }
public override string ToString() => $"{FirstName} {LastName}";
}
Mocked data
public class MockedData
{
public static List<Customer> Customers() => new List<Customer>()
{
new Customer()
{
CustomerIdentifier = 1, FirstName = "Jim", LastName = "Adams",
Street = "120 Hanover Sq.", City = "London", PostalCode = "WA1 1DP",
CountryIdentifier = 19
},
new Customer()
{
CustomerIdentifier = 2, FirstName = "Mary", LastName = "Adams",
Street = "1 rue Alsace-Lorraine", City = "Toulouse", PostalCode = "31000",
CountryIdentifier = 8
},
new Customer()
{
CustomerIdentifier = 3, FirstName = "Karen", LastName = "White",
Street = "120 Hanover Sq.", City = "London", PostalCode = "WA1 1DP",
CountryIdentifier = 19
}
};
}
Form code
public partial class Form1 : Form
{
private readonly BindingList<Customer> _customersBindingList;
public Form1()
{
InitializeComponent();
_customersBindingList = new BindingList<Customer>(MockedData.Customers());
listBoxCustomers.DataSource = _customersBindingList;
}
private void RemoveCurrentButton_Click(object sender, EventArgs e)
{
if (listBoxCustomers.SelectedIndex > -1)
{
_customersBindingList.RemoveAt(listBoxCustomers.SelectedIndex);
}
RemoveCurrentButton.Enabled = listBoxCustomers.SelectedIndex > -1;
}
}
Here is the function to remove all customers with a certain id :
private void RemoveCustomer(int id)
{
list.RemoveAll(c => c.customerId == id);
}
Related
In my MdiForm I have a menubar that has btnSave on it. I would like to save the data created in my childform that is active by clicking the btnSave on the midForm menubar. I have these classes to save the data to the database:
StudentBal.cs
internal class StudentBal
{
public string DateAdded { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string CityAddress { get; set; }
public string HomeAddress { get; set; }
public string Nationality { get; set; }
public string MaritalStatus { get; set; }
public string DateOfBirth { get; set; }
public string PlaceOfBirth { get; set; }
public string TelNo { get; set; }
public string Father { get; set; }
public string Mother { get; set; }
public string ParentsAddress { get; set; }
public string EmployersName { get; set; }
public string EmplyerTelNo { get; set; }
public string GuardiansName { get; set; }
public string GuradiansAddress { get; set; }
public byte[] StudentImage { get; set; }
public string WorkAddress { get; set; }
public int InsertStudent(StudentBal bal)
{
var dal = new StudentDal();
return dal.InsertStudent(bal);
}
StudentDal.cs
public int InsertStudent(StudentBal bal)
{
const string query =
#"INSERT INTO students VALUES(#DateAdded, #FirstName, #MiddleName, #LastName, #CityAddress, #HomeAddress, #Nationality,
#MaritalStatus, #DateOfBirth, #PlaceOfBirth, #TelNo, #Father, #Mother,
#ParentsAddress, #EmployersName, #EmployersTelNo, #GuardiansName,
#GuardiansAddress, #StudentImage, #WorkAddress)";
using (_cmd = new SqlCommand(query, _cn))
{
_cmd.Parameters.AddWithValue("#DateAdded", Convert.ToDateTime(bal.DateAdded).ToShortDateString());
_cmd.Parameters.AddWithValue("#FirstName", bal.FirstName);
_cmd.Parameters.AddWithValue("#MiddleName", bal.MiddleName);
_cmd.Parameters.AddWithValue("#LastName", bal.LastName);
_cmd.Parameters.AddWithValue("#CityAddress", bal.CityAddress);
_cmd.Parameters.AddWithValue("#HomeAddress", bal.HomeAddress);
_cmd.Parameters.AddWithValue("#Nationality", bal.Nationality);
_cmd.Parameters.AddWithValue("#MaritalStatus", bal.MaritalStatus);
_cmd.Parameters.AddWithValue("#DateOfBirth", bal.DateOfBirth);
_cmd.Parameters.AddWithValue("#PlaceOfBirth", bal.PlaceOfBirth);
_cmd.Parameters.AddWithValue("#TelNo", bal.TelNo);
_cmd.Parameters.AddWithValue("#Father", bal.Father);
_cmd.Parameters.AddWithValue("#Mother", bal.Mother);
_cmd.Parameters.AddWithValue("#ParentsAddress", bal.ParentsAddress);
_cmd.Parameters.AddWithValue("#EmployersName", bal.EmployersName);
_cmd.Parameters.AddWithValue("#EmployersTelNo", bal.EmplyerTelNo);
_cmd.Parameters.AddWithValue("#GuardiansName", bal.GuardiansName);
_cmd.Parameters.AddWithValue("#GuardiansAddress", bal.GuradiansAddress);
_cmd.Parameters.AddWithValue("#StudentImage", bal.StudentImage);
_cmd.Parameters.AddWithValue("#WorkAddress", bal.WorkAddress);
_cn.Open();
return(_cmd.ExecuteNonQuery());
}
}
This is in my AddStudent Form
private void btnSaveInformation_Click(object sender, EventArgs e)
{
var stream = new MemoryStream();
pictureBox2.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
if (!CheckTextBox()) return;
var bal = new StudentBal
{
CityAddress = string.IsNullOrWhiteSpace(txtCityAddress.Text) ? "N/A" : txtCityAddress.Text,
DateAdded = DateTime.Now.ToShortDateString(),
DateOfBirth = txtDateOfBirth.Text,
EmployersName = string.IsNullOrWhiteSpace(txtEmployersName.Text) ? "N/A" : txtEmployersName.Text,
EmplyerTelNo = string.IsNullOrWhiteSpace(txtEmpContactNumber.Text) ? "N/A" : txtEmpContactNumber.Text,
Father = string.IsNullOrWhiteSpace(txtFathersName.Text) ? "N/A" : txtFathersName.Text,
FirstName = txtFirstName.Text,
GuardiansName = string.IsNullOrWhiteSpace(txtGuardiansName.Text) ? "N/A" : txtGuardiansName.Text,
GuradiansAddress = string.IsNullOrWhiteSpace(txtGuardiansAddress.Text) ? "N/A" : txtGuardiansAddress.Text,
HomeAddress = txtHomeAddress.Text,
LastName = txtLastName.Text,
MaritalStatus = txtMaritalStatus.Text,
MiddleName = string.IsNullOrWhiteSpace(txtMiddleName.Text) ? "N/A" : txtMiddleName.Text,
Mother = txtMothersName.Text,
Nationality = txtNationality.Text,
ParentsAddress = txtParentsAddress.Text,
PlaceOfBirth = txtPlaceOfBirth.Text,
TelNo = string.IsNullOrWhiteSpace(txtTelNo.Text) ? "N/A" : txtTelNo.Text,
StudentImage = pic,
WorkAddress = string.IsNullOrWhiteSpace(txtWorkAddress.Text) ? "N/A" : txtWorkAddress.Text,
};
var result = bal.InsertStudent(bal);
if (result > 0)
{
MessageBox.Show(#"Data successfully added.");
}
var obj = (MdiForm)Application.OpenForms["MdiForm"];
if (obj != null) obj.FillComboBox();
}
I would need to pass all the information from my childform(AddStudent) to the parentform(MdiFOrm) so I can save all the details by clicking on the btnSave in the menubar. I tried creating a public method (SaveDetails()) that can be invoked in the parent form like so:
AddStudent add = new AddStudent();
add.SaveDetails();
But doing the code above will create a new instance and will not save the active childform that has the values to be saved. If there is a way to call a method in the active childform without instantiating (var addStudent = new AddStudent();) that will be great.
Making the method public static won't work in this scenario.
Thank you for your help.
This is the abstract example of doing a callback:
public class Parent
{
public void CreateChild()
{
Child childNew = new Child(this); //here you give over the parents reverence
}
public void SaveStuff(int number)
{
//here you can save the number
}
}
class Child
{
private Parent parent;
public Child(Parent parent)
{
this.parent = parent;
}
public void PressOkButton()
{
this.parent.SaveStuff(4); //here you are doing the callback
}
}
Ok, so I have been facing this issue several times now but I always seemed to figure it out.
This time, ive been stuck and ive tried multiple things, but nothing is working.
I have a combobox of customers in a customer form. When i create a new customer, my combobox is not updating. It only refreshes when closing and re-opening the form.
I am aware of the "ugly and quick" solutions, but I don't want to use this unless I have no other choise. So ive been using BindingLists because of the events... BUT this is not working in my case.
Ive been staring to this for a time now, let it aside, tried again, but keep on failing.
Does anyone know whats missing in this puzzle?
Now the code: Presenter
public class CustomerPresenter
{
private tbl_customer customer = new tbl_customer();
private CustomerView customerView = new CustomerView();
public CustomerPresenter(tbl_customer customer, CustomerView customerView)
{
this.customer = customer;
this.customerView = customerView;
customerView.customerPresenter = this;
}
// Get a list of customers
public List<tbl_customer> customerList;
public BindingList<tbl_customer> getCustomers()
{
using (var customers = new DBCrownfishEntities())
{
var customer = from c in customers.tbl_customer
where c.IsDeleted == false
select c;
this.customerList = customer.ToList();
var listBinding = new BindingList<tbl_customer>(this.customerList);
return listBinding;
}
}
public void testAdd()
{
tbl_customer customer = new tbl_customer();
customer.CustomerPrefix = "Pref";
customer.CustomerName = "Name";
customer.CustomerAddress = "Address";
customer.CustomerPostalCode = "1111";
customer.CustomerCity = "City";
customer.CustomerCountry = "Country";
customer.CustomerCountryCode = "BE";
customer.CustomerVat = "123456789";
customer.hasVatNumber = true;
try
{
using (var cust = new DBCrownfishEntities())
{
cust.tbl_customer.Add(customer);
cust.SaveChanges();
MessageBox.Show("A new customer is succesfully added!");
}
}
catch (EntityException exception)
{
MessageBox.Show(exception.InnerException.Message.ToString(), "Error Connecting database");
}
catch (Exception)
{
throw;
}
}
}
View:
BindingSource bsCustomers = new BindingSource();
private void CustomerView_Load(object sender, EventArgs e)
{
bsCustomers.DataSource = customerPresenter.getCustomers();
cbCustomers.DataSource = bsCustomers;
cbCustomers.DisplayMember = "CustomerName";
cbCustomers.ValueMember = "CustomerId";
radioButton1_CheckedChanged(null, null);
}
private void button1_Click_1(object sender, EventArgs e)
{
customerPresenter.testAdd();
}
Model:
public partial class tbl_customer
{
public tbl_customer()
{
this.tbl_invoices = new HashSet<tbl_invoices>();
}
public int CustomerID { get; set; }
public string CustomerPrefix { get; set; }
public string CustomerName { get; set; }
public string CustomerEmailaddress { get; set; }
public string CustomerAddress { get; set; }
public string CustomerPostalCode { get; set; }
public string CustomerCity { get; set; }
public string CustomerVat { get; set; }
public string CustomerCountryCode { get; set; }
public string CustomerCountry { get; set; }
public bool IsDeleted { get; set; }
public bool hasVatNumber { get; set; }
public virtual ICollection<tbl_invoices> tbl_invoices { get; set; }
}
I want to make a application which show record from database, and I can add new record. I first time use a database in C# so I have completely nobie in this topic. When I click button Accept, than compilator show "An unhandled exception occured.". I don't know what I'm doing wrong.
My code:
public class Person
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string CellPhoneNumber { get; set; }
public string EMailAddress { get; set; }
public Person() { }
public Person(string firstName, string lastName, string address, string cellPhoneNumber, string eMailAddress)
{
FirstName = firstName;
LastName = lastName;
Address = address;
CellPhoneNumber = cellPhoneNumber;
EMailAddress = eMailAddress;
}
}
public class PersonDatabase
{
public SQLiteConnection connection;
static string baseName = "Person.db";
static string basePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
static string path = Path.Combine(basePath, baseName);
public PersonDatabase()
{
// If database don't exist then, will created new file. Else open exist file.
if (!File.Exists(path))
{
connection = new SQLiteConnection(path);
connection.CreateTable<Person>();
}
connection = new SQLiteConnection(path);
}
public PersonDatabase(Person person) : base()
{
//person.Id = connection.Table<Person>().Count() + 1;
connection.Insert(person);
connection.Update(person);
}
}
public class MainActivity : Activity
{
public PersonDatabase database = new PersonDatabase();
private List<Person> personList = new List<Person>();
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
var addButton = FindViewById<Button>(Resource.Id.addButton);
var query = database.connection.Table<Person>();
foreach (var person in query)
{
personList.Add(person);
}
var listView = FindViewById<ListView>(Resource.Id.listView);
listView.Adapter = new ListViewAdapter(this, personList);
addButton.Click += (object sender, EventArgs e) =>
{
StartActivity(typeof(FormActivity));
};
}
}
[Activity(Label = "FormActivity")]
public class FormActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Form);
var firstName = FindViewById<EditText>(Resource.Id.editTextFirstName);
var lastName = FindViewById<EditText>(Resource.Id.editTextLastName);
var address = FindViewById<EditText>(Resource.Id.editTextAddress);
var cellPhoneNumber = FindViewById<EditText>(Resource.Id.editTextCellNumber);
var eMailAddress = FindViewById<EditText>(Resource.Id.editTextMail);
var acceptButton = FindViewById<Button>(Resource.Id.acceptButton);
acceptButton.Click += (object sender, EventArgs e) =>
{
Person newPerson = new Person(firstName.Text, lastName.Text, address.Text, cellPhoneNumber.Text, eMailAddress.Text);
var personDatabase = new PersonDatabase(newPerson);
StartActivity(typeof(MainActivity));
Finish();
};
}
}
I am having a major issue making this work. All I need to do is make my array display.
namespace OOP_3
{
public partial class Add_Child : Form
{
public Add_Child()
{
InitializeComponent();
}
private void btnAddChild_Click(object sender, EventArgs e)
{
Mother m = new Mother();
m.MyChildren = new Child[3];
int ID = int.Parse(txtID.Text);
string FNAME = txtFname.Text;
string LName = txtLname.Text;
DateTime DOB = DateTime.Parse(txtDob.Text);
//Add children
label5.Text = m.GetMyChildrenDetails();
if (addtoarray(m,ID,FNAME,LName,DOB) == true)
{
MessageBox.Show("added", "Add Child");
}
else
{
MessageBox.Show("cannot add", "Child add - full");
}
}
public bool addtoarray(Mother m, int ID, string FNAME, string LName,DateTime DOB)
{
for (int i = 0; i < m.MyChildren.Length; i++)
{
if (m.MyChildren[i]== null)
{
m.MyChildren[i] = new Child(m); //See comment below
m.MyChildren[i].ChildId = ID;
m.MyChildren[i].FirstName = FNAME;
m.MyChildren[i].LastName = LName;
m.MyChildren[i].DateOfBirth = DOB;
return true;
}
}
return false;
}
}
}
From a code comment: This line destroys everything in the heap and recreate the array causing my to have values that will not show up in my label5.text ive been pondering researching for hours and i think iam either going insane or am just noobie at coding which iam :) please some help would be nice:)....
If needed, I will post my class's and main form up :)
public class Mother
{
//Fields
private int motherId;
private string firstName;
private string lastName;
private string mobile;
private Child[] myChildren; //mother "has a" many children
//props
public Child[] MyChildren
{
get { return myChildren; }
set { myChildren = value; }
}
public string Mobile
{
get { return mobile; }
set { mobile = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public int MotherId
{
get { return motherId; }
set { motherId = value; }
}
//constructors
//methods
//Get Mother Details
public override string ToString()
{
return motherId + ", " + firstName + ", " + lastName + ", " + mobile;
}
//AddChild
public bool AddChild(Child myChild)
{
for (int i = 0; i < myChildren.Length; i++)
{
if (myChildren[i] != null)
{
myChildren[i] = myChild;
return true;
}
}
return false;
}
//GetMyChildrenDetails
public string GetMyChildrenDetails()
{
string msg = "";
for (int i = 0; i < myChildren.Length; i++)
{
if (myChildren[i] != null)
{
msg += "\n" + myChildren[i];
}
}
return msg;
}
public class Child
{
//fields
private int childId;
private string firstName;
private string lastName;
private DateTime dateOfBirth;
private Mother myMother; //child "has a" mother
//props
public Mother MyMother
{
get { return myMother; }
set { myMother = value; }
}
public DateTime DateOfBirth
{
get { return dateOfBirth; }
set { dateOfBirth = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public int ChildId
{
get { return childId; }
set { childId = value; }
}
//constructors
//Child cannot be created without a mother
public Child(Mother myMother)
{
this.myMother = myMother;
}
//Child cannot be created without a mother
public Child(Mother myMother, int childId)
{
this.myMother = myMother;
this.childId = childId;
}
//methods
//Get Child Details
public override string ToString()
{
return childId + ", " + firstName + ", " + lastName + ", " + dateOfBirth;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnRegister_Click(object sender, EventArgs e)
{
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void BtnAddChild_Click(object sender, EventArgs e)
{
Add_Child child = new Add_Child();
child.Show();
}
private void btnRegister_Click_1(object sender, EventArgs e)
{
//create a mother object
Mother m = new Mother();
m.MotherId = int.Parse(txtID.Text);
m.FirstName = txtFname.Text;
m.LastName = txtLname.Text;
m.Mobile = txtMobile.Text;
Giving the new child a reference to its parent object is not the cause of your issue. In summary, you state:
"to have values that will not show up in my label5.text "
This would indicate that it is either your binding that has an issue, you have not implemented INotifyPropertyChanged, or your UI updating mechanism is not working (if you are not using binding). As you haven't stated what you are using for the UI, that is about as much as I can help...
My suggestion, you may use List instead of array, because not all mothers have three children. Example code:
public static class Program
{
static void Main(string[] args)
{
Mother mother = new Mother {
FirstName = "M First", LastName = "M Last", Contact = "225632655"
};
//Add dependents
mother.AddChild(new Child{ChildID = 1, FirstName = "Child FirstName 1", LastName = "Child LastName 1"});
mother.AddChild(new Child{ChildID = 2, FirstName = "Child FirstName 2", LastName = "Child LastName 2"});
mother.AddChild(new Child{ChildID = 3, FirstName = "Child FirstName 3", LastName = "Child LastName 3"});
Console.WriteLine(mother);
//List all the mother dependents
foreach(Child c in mother.Children)
{
Console.WriteLine(c);
}
Console.ReadKey();
}
}
class Mother
{
public string FirstName {get; set;}
public string LastName {get; set;}
public string Contact {get; set;}
private List<Child> _child;
public Mother()
{
_child = new List<Child>();
}
public void AddChild(Child child)
{
_child.Add(child);
}
public List<Child> Children
{
get { return _child; }
}
public override string ToString()
{
return string.Format("{0}, {1} ({2})", LastName, FirstName, Contact);
}
}
class Child
{
public string FirstName {get; set;}
public string LastName {get; set;}
public int ChildID {get; set;}
public override string ToString()
{
return string.Format("{0} {1}, {2}", ChildID, LastName, FirstName);
}
}
I hope, this will help.
Class Person
{
string Name
int yesno
int Change
List<Cars> Personcars;
houses Personhouses
}
Person user1 = new Person()
Person user2 = new Person()
user1.Name = "userName"
user2.Name ="";
user2.cars[0] = new car("Mazda");
user1.cars[0] = new car("BMW");
i want to merge the objects so that user2 will take the name and the car from user1
user2 will have this values
user2.Name will be userName
user2.cars will hold the Mazda and the Bmw
thanks !
user2.Name = user1.Name;
user2.Personcars.AddRange(user1.Personcars);
You could add this as a method on the class itself:
public class Person
{
List<Cars> _personcars;
public string Name { get; set; }
// what the hell is a yesno int? If it's 1 or 0 then just use a bool
public int yesno { get; set; }
public int Change { get; set; }
public List<Cars> Personcars
{
get
{
return _personcars ?? (_personCars = new List<Cars>());
}
set { _personcars = value; }
}
public Houses Personhouses { get; set; }
public void Merge(Person person)
{
Name = person.Name;
Personcars.AddRange(person.Personcars);
}
}
Which will allow you to write something like this:
user2.Merge(user1);
Try this extension methods
public void Merge(this Person _person, Person source)
{
_person.Name = source.Name;
if(_person.Cars !=null)
{
_person.Cars.AddRang(source.Cars);
}
else
{
_person.Cars = source.Cars;
}
}