I wrote a few code line in c# to iterate through a list, but i print in the textbox only the last one. the code that i wrote:
//For instantiation
Account account = new Account(0,"","", 0);
//A list for class Account
List<Account> listAccount = new List<Account>();
//Button for adding new Customer
private void button1_Click(object sender, EventArgs e)
{
account.CustomerID = int.Parse(customerIdTxt.Text);
account.CustomerFullName = customerNameTxt.Text;
account.CustomerAddress = customerAddrTxt.Text;
listAccount.Add(account);
}
//For printing the Customer's detailes in textbox
private void button6_Click(object sender, EventArgs e)
{
string showCustDetailes = "";
for(int i=0;i<listAccount.Count;i++)
{
showCustDetailes+=
"Customer ID : " + listAccount[i].CustomerID + Environment.NewLine +
"Customer Name : " + listAccount[i].CustomerFullName + Environment.NewLine +
"Customer Address : " + listAccount[i].CustomerAddress + Environment.NewLine +
"---------------------------------------------------" + Environment.NewLine;
}
viewDetailesTxt.Text = showCustDetailes;
}
can anyone help me how can i print the whole customers list
There's nothing wrong with the code that loops over the list (apart from not using foreach()). If you really only see one account, the problem is in displaying: make your textbox bigger or give it scrollbars.
Also, you're editing the same instance of account every time, so you're filling your list with multiple references to the same account. You must use new Account to instantiate a new one for every "button 1" click:
private void button1_Click(object sender, EventArgs e)
{
Account account = new Account(0,"","", 0);
// ...
listAccount.Add(account);
}
List<Account> listAccount = new List<Account>();
private void button1_Click(object sender, EventArgs e)
{
var account = new Account {
CustomerID = int.Parse(customerIdTxt.Text),
CustomerFullName = customerNameTxt.Text,
CustomerAddress = customerAddrTxt.Text
};
listAccount.Add(account);
}
private void button6_Click(object sender, EventArgs e)
{
var sb = new StringBuilder();
foreach(var account in listAccount)
{
sb.AppendFormat("Customer ID: {0}\nCustomer Name: {1}\nCustomer Address: {2}\n\n", account.CustomerID, account.CustomerFullName, account.CustomerAddress);
}
viewDetailesTxt.Text = sb.ToString();
}
Related
Why List return empty when execute 2nd event?
List<string> ErrorList = new List<string>();
protected void Page_Load(object sender, EventArgs e){}
protected void btnFirst_Click(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
ErrorList.Add(i);
}
txtResult.Text = "Length of list: " + ErrorList.Count;
}
protected void btnSecond_Click(object sender, EventArgs e)
{
txtResult.Text = "Length of list: " + ErrorList.Count;
}
When click btnFirst: txtResult.Text = "Length of list: 5"
When click btnSecond: txtResult.Text = "Length of list: 0"
Try this code but it only work if cookies enabled on client side
The session is a container located server side. In the cookie on client (browser) is a id to make a relation with the session. It is also possible to save more informations in a cookie but i would not recommend it. All other informations infos are lost every request.
protected void Page_Load(object sender, EventArgs e){}
protected void btnFirst_Click(object sender, EventArgs e)
{
List<string> ErrorList = new List<string>();
for (int i = 0; i < 5; i++)
{
ErrorList.Add(i);
}
Session["Errors"] = ErrorList;
txtResult.Text = "Length of list: " + ErrorList.Count;
}
protected void btnSecond_Click(object sender, EventArgs e)
{
List<string> ErrorList = (List<string>)Session["Errors"];
txtResult.Text = "Length of list: " + ErrorList.Count;
}
I need to accept more than one value from the same textbox and store it into an arrya . I need something close to the below code :
string[] countries = new string[3];
private void accept_Click(object sender, EventArgs e)
{
countries[0] = textBox1.Text+" 1 ";
countries[1] = textBox1.Text + " 2 ";
countries[2] = textBox1.Text + " 3 ";
}
private void finish_Click(object sender, EventArgs e)
{
foreach (string coun in countries)
MessageBox.Show("You have entered " + coun);}
}
}
How do you split the different countries?
If you split it on each space you can do it like this:
string[] countries = textBox1.Text.Split(null);
If that is not a good solution maybe try and explain the expected output.
You can simply use a multiline textbox and split the input on newlines:
var countries = countriesTextBox.Text.Split(Environment.NewLine);
Why not just use a list? The following code will add the country's name entered in the textbox to the List<string> every time you click the accept button.
var countries = new List<string>();
private void accept_Click(object sender, EventArgs e)
{
countries.Add(textBox1.Text);
}
private void finish_Click(object sender, EventArgs e)
{
foreach (string coun in countries)
MessageBox.Show("You have entered " + coun);
}
If you want to allow the user to enter multiple countries at once, the following will work if you put a comma in between each country name when entering them into the textbox:
var countries = new List<string>();
private void accept_Click(object sender, EventArgs e)
{
var input = textBox1.Text.Split(',');
countries.AddRange(input);
}
private void finish_Click(object sender, EventArgs e)
{
foreach (string coun in countries)
MessageBox.Show("You have entered " + coun);
}
Working on a project for school that has 2 forms. I want to add items to the listbox in the Display form when I click the show data button. It's showing the form but the form is blank. I think this is because the form object is being created 2x once when I click the add button and another when I click the show data button. How can I create a new object of the display form that can be used in any method in my main form?
Sorry there is a few things in here that I am still working on that were just ideas. I am a beginner so please keep the help in simple terms if at all possible. Thanks :)
private void addEmployee(Employee newEmployee)
{
//Get data from textboxes and use set methods in employee class
newEmployee.Name = EmployeeNameTextBox.Text;
newEmployee.BirthDate = EmployeeBirthDateTextBox.Text;
newEmployee.Dept = EmployeeDeptTextBox.Text;
newEmployee.HireDate = EmployeeHireDateTextBox.Text;
newEmployee.Salary = EmployeeSalaryTextBox.Text;
}
private void AddButton_Click(object sender, EventArgs e)
{
//New list for employee class objects - employeelist
List<Employee> employeeList = new List<Employee>();
//Create new instance of Employee class - newEmployee
Employee newEmployee = new Employee();
bool errorCheck = false;
CheckForms(ref errorCheck);
if (!errorCheck)
{
//Gather input from text boxes and pass newEmployee object
addEmployee(newEmployee);
//Add object to employeeList
employeeList.Add(newEmployee);
Display myDisplay = new Display();
myDisplay.OutputListBox.Items.Add(" Bob");
//" " + newEmployee.BirthDate + " " +
//newEmployee.Dept + " " + newEmployee.HireDate + " " + newEmployee.Salary);
You are creating two separate instances of mydisplay.Create a single instance when the Form Loads and refer to that when you call ShowDataButton_Click
namespace WK4
{
public partial class MainForm : Form
{
Display myDisplay;
public MainForm()
{
InitializeComponent();
}
//Method to clear form input boxes
private void ClearForm()
{
EmployeeNameTextBox.Text = "";
EmployeeBirthDateTextBox.Text = "";
EmployeeDeptTextBox.Text = "";
EmployeeHireDateTextBox.Text = "";
EmployeeSalaryTextBox.Text = "";
FooterLabel.Text = "";
}
//Method to check for blank input on textboxes
private void CheckForms(ref bool error)
{
if (EmployeeNameTextBox.Text == "" || EmployeeBirthDateTextBox.Text == "")
{
MessageBox.Show("Please do not leave any fields blank");
error = true;
}
else if (EmployeeDeptTextBox.Text == "" || EmployeeHireDateTextBox.Text == "")
{
MessageBox.Show("Please do not leave any fields blank");
error = true;
}
else if (EmployeeSalaryTextBox.Text == "")
{
MessageBox.Show("Please do not leave any fields blank");
error = true;
}
else
error = false;
}
private void addEmployee(Employee newEmployee)
{
//Get data from textboxes and use set methods in employee class
newEmployee.Name = EmployeeNameTextBox.Text;
newEmployee.BirthDate = EmployeeBirthDateTextBox.Text;
newEmployee.Dept = EmployeeDeptTextBox.Text;
newEmployee.HireDate = EmployeeHireDateTextBox.Text;
newEmployee.Salary = EmployeeSalaryTextBox.Text;
}
private void AddButton_Click(object sender, EventArgs e)
{
//New list for employee class objects - employeelist
List<Employee> employeeList = new List<Employee>();
//Create new instance of Employee class - newEmployee
Employee newEmployee = new Employee();
bool errorCheck = false;
CheckForms(ref errorCheck);
if (!errorCheck)
{
//Gather input from text boxes and pass newEmployee object
addEmployee(newEmployee);
//Add object to employeeList
employeeList.Add(newEmployee);
Display myDisplay = new Display();
myDisplay.OutputListBox.Items.Add(" Bob");
//" " + newEmployee.BirthDate + " " +
//newEmployee.Dept + " " + newEmployee.HireDate + " " + newEmployee.Salary);
//Clear Form after adding data
ClearForm();
//Print footer employee saved info
FooterLabel.Text = ("Employee " + newEmployee.Name + " saved.");
}
}
//Exit the form/program
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
//Method to clear the form and reset focus
private void ClearButton_Click(object sender, EventArgs e)
{
ClearForm();
EmployeeNameTextBox.Focus();
}
private void ShowDataButton_Click(object sender, EventArgs e)
{
myDisplay.ShowDialog();
}
private void MainForm_Load(object sender, EventArgs e)
{
myDisplay = new Display();
}
}
}
You are making 2 different instances of display class, in first instance you are adding data and you are displaying it using the second instance thats why you are getting a blank form
create a display class object on your MainForm_Load
private void MainForm_Load(object sender, EventArgs e)
{
Display myDisplay = new Display();
}
and the use this object (myDisplay) to add and display data in your AddButton_Click and ShowDataButton_Click methods respectively.
I have 3 checkboxes with corresponding message in a textbox. My teacher wants the message to remain in the textbox when the checkbox is still checked and hide the text when it is unchecked. In my case when I checked the 3 checkboxes their 3 corresponding messages will appear but when I unchecked one of the checkboxes and the other two are still checked, all the message will disappear. My problem is when I unchecked one of the checkbox and and the other 2 are still checked the corresponding messages with the remaining two checked checkboxes will remain in their textboxes.
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
if (chkCarWheels.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.hasWheels(4);
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
if (chkCarAcceleration.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.Accelerate();
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
if (chkCarBreakpad.Checked == true)
lblMessage.Text = lblMessage.Text + mycar.hasBreak();
else
lblMessage.Text = "My " + txtName.Text + " Car";
}
Looks like you need to create message depending on checkboxes states. You can create method, which will do the job and call it when state of some checkbox changed.
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
Or the better one - create one event handler for all checkboxes:
// use for chkCarWheels, chkCarAcceleration, chkCarBreakpad
private void chkCar_CheckedChanged(object sender, EventArgs e)
{
BuildMessage();
}
private void BuildMessage()
{
lblMessage.Text = "My " + txtName.Text + " Car";
if (chkCarWheels.Checked)
lblMessage.Text = lblMessage.Text + mycar.hasWheels(4);
if (chkCarAcceleration.Checked)
lblMessage.Text = lblMessage.Text + mycar.Accelerate();
if (chkCarBreakpad.Checked)
lblMessage.Text = lblMessage.Text + mycar.hasBreak();
}
You don't need to compare boolean values with true/false. Use those values directly if (chkCarWheels.Checked). And keep in mind that in C# we use CamelCase names form methods. Also consider to use StringBuilder to build whole message and then assign it to label:
private void BuildMessage()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("My {0} Car", txtName.Text);
if (chkCarWheels.Checked)
sb.Append(mycar.hasWheels(4));
if (chkCarAcceleration.Checked)
sb.Append(mycar.Accelerate());
if (chkCarBreakpad.Checked)
sb.Append((mycar.hasBreak());
lblMessage.Text = sb.ToString();
}
Try this:
private void chkCarWheels_CheckedChanged(object sender, EventArgs e)
{
chkCar();
}
private void chkCarAcceleration_CheckedChanged(object sender, EventArgs e)
{
chkCar();
}
private void chkCarBreakpad_CheckedChanged(object sender, EventArgs e)
{
chkCar()
}
private void chkCar()
{
string msg="";
if (chkCarWheels.Checked)
msg=msg+mycar.hasWheels(4);
if(chkCarAcceleration.Checked)
msg=msg+mycar.Accelerate();
if(chkCarBreakpad.Checked)
msg=msg+mycar.hasBreak();
lblMessage.Text=msg;
}
I have a listview with subitems. The first 5 sub items are the name, items, total price, address and telephone.
The rest of the subitems contain the past list that I displayed for my order.
It is a pizzeria program and I want it to be able to get the customers info and order.
I can get the info but can't get the rest of the order.
I'm wondering how I can display the rest of my order if that makes sense.
Example Order:
Name: Claud
Items: 3
Total: 10.99
Address: (Blank)
Telephone: (Blank)
Order: Small Pizza
-Bacon
BreadSticks
Right now my messagebox looks like this:
Name: Claud
Items: 3
Total: 10.99
Address: (Blank)
Telephone: (Blank)
Order: Small Pizza
So I just want it to display the -Bacon and BreadSticks.
Source Code:
private void CustomerInfo_Click(object sender, EventArgs e)
{
ListViewItem customers = new ListViewItem(fullName.Text);
customers.SubItems.Add(totalcount.ToString());
customers.SubItems.Add(total.ToString());
customers.SubItems.Add(Address.Text);
customers.SubItems.Add(telephone.Text);
for (int i = 0; i < OrderlistBox.Items.Count; i++)
{
customers.SubItems.Add(OrderlistBox.Items[i].ToString());
}
Customers.Items.Add(customers);
MessageBox.Show("Sent order for " + fullName.Text.ToString() + " to screen.");
//CLEAR ALL FIELDS
OrderlistBox.Items.Clear();
fullName.Text = "";
Address.Text = "";
telephone.Text = "";
totalDue.Text = "";
totalItems.Text = "";
}
private void customerInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Customers.SelectedItems.Count != 0)
{
MessageBox.Show("Name: " + Customers.SelectedItems[0].SubItems[0].Text + "\n" +
"Adress: " + Customers.SelectedItems[0].SubItems[3].Text + "\n" +
"Telephone: " + Customers.SelectedItems[0].SubItems[4].Text + "\n" +
"Order: " +Customers.SelectedItems[0].SubItems[5].Text);
}
}
You can create custom message box by creating new winform that act as your messagebox.
Create public property on it to pass the value of your selecteditems something like:
Then on your form :
private void customerInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Customers.SelectedItems.Count != 0)
{
var myformmessagedialog = new MyFormMessageDialog
{
name = Customers.SelectedItems[0].SubItems[0].Text,
adress=Customers.SelectedItems[0].SubItems[3].Text,
telephone=Customers.SelectedItems[0].SubItems[4].Text
};
myformmessagedialog.ShowDialog();
}
}
Your MessageBoxDialogform:
MyFormMessageDialog : Form
{
public MyFormMessageDialog()
{
InitializeComponent();
}
public string name;
public string adress;
public string telephone;
private void MyFormMessageDialog_Load(object sender, EventArgs e)
{
lblName.Text = name;
lbladdress.Text = adress;
telephone.Text telephone;
//if you are saving ado.net stuff
//query username where name = name then bind it on a list box or a combo box
var Orderdata = //you retrieve info via DataTable;
lstOder.Items.Clear();
foreach (DataRow data in Orderdata.Rows)
{
var lvi = new ListViewItem(data["Order"].ToString());
// Add the list items to the ListView
lstlstOder.Items.Add(lvi);
}
}
}
Hope this help you.
Regards