C# accept a value more than once from textbox - c#

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);
}

Related

Add the same string from textbox in two lines listbox?

Is it possible to add the same string typed in the texbox in the two lines of the listbox, as shown in the image below?
private void metroButton10_Click(object sender, EventArgs e)
{
listBox2.Items.Add("Next station: " + metroTextBox1.Text);
listBox2.Items.Add(Environment.NewLine)
metroTextBox1.Clear();
listBox2.SelectedIndex = 0;
}
Use the following code.
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add("Next Station: "+textBox1.Text);
listBox1.Items.Add("Station: " + textBox1.Text);
}
You Can't use new line. Because listbox can contain one item in a line.
Sure you can add same string typed in the textbox in the two lines of the listbox as;
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add("NextStation: " + textBox1.Text);
listBox1.Items.Add("Station: " +textBox1.Text);
}

loop through list in c#

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();
}

Display all values of Hashtable through button

Okay so I'm trying to display multiple values in hashtable through my button. But it keeps on showing me the first value but not the others.
public Form1()
{
InitializeComponent();
}
Hashtable Info = new Hashtable();
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
Info.Add(a,b);
label4.Text = a + " " + b;
}
private void button3_Click(object sender, EventArgs e)
{
foreach (DictionaryEntry DE in Info)
{
label4.Text = ""+ DE.Key +DE.Value; //this only shows the first added value. How do I show the remaining values?
}
}
This is because each iteration of the loop replaces the previous value in the text. You can fix this by clearing out the text before going into the loop, and using += instead of =:
label4.Text += " "+ DE.Key +DE.Value
A better approach would be to use string.Join for this:
private void button3_Click(object sender, EventArgs e) {
label4.Text = string.Join(
", "
, Info.Select(p => string.Format("{0}-{1}", p.Key, p.Value))
);
}
I recommend you don't keep changing label4.Text in the loop, but build a string in the loop and change it once at the end. Something like:
StringBuilder allEntries = new StringBuilder();
foreach (DictionaryEntry DE in Info)
{
allEntries.Append(DE.Key);
allEntries.Append(DE.Value);
}
label4.Text = allEntries.ToString();
[I edited an earlier version of the code that didn't compile.]
KC

Retain the message in the textbox when the checkbox is still checked

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;
}

Search a file that was created

When I create the file and append to it the rest of the information I now want to have the ability to read the text file then display the Month of a birthday thats listed in the file.
I want to be able to pull in just the info by birthday. So if I choose month 11 I want to pull in all the data entries that have a birthmonth of 11 by pushing button4.
This is what I have so far;
private void close_Click(object sender, EventArgs e)
{
Close();
}
private void button1_Click(object sender, EventArgs e)
{
writetext();
reset();
}
public void writetext()
{
using (TextWriter writer = File.AppendText("filename.txt"))
{
writer.WriteLine("First name, {0} Lastname, {1} Phone,{2} Day of birth,{3} Month of Birth{4}", textBox1.Text, textBox2.Text, maskedTextBox1.Text, textBox4.Text, textBox3.Text);
MessageBox.Show(String.Format("First Name,{0} Lastname, {1} Phone,{2} Day of birth,{3} Month of Birth{4}", textBox1.Text, textBox2.Text, maskedTextBox1.Text, textBox4.Text, textBox3.Text));
}
}
public void reset()
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
maskedTextBox1.Text = "";
}
private void button3_Click(object sender, EventArgs e)
{
Close();
}
private void button2_Click(object sender, EventArgs e)
{
readfile();
}
private void label7_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
}
public void readfile()
{
string[] lines = File.ReadAllLines("filename.txt");
label6.Text = String.Join(Environment.NewLine, lines);
}
}
}
Same as Geoffrey but with C# and linq syntax:
You can filter the content of your file using the birth date and store it in a new array this way:
string[] persons = File.ReadAllLines(Server.MapPath("filename.txt"));
IEnumerable<string> personsWithBirthday =
from p in persons
where p.Contains("1980-08-21")
select p;
foreach (var person in personsWithBirthday)
Response.Write(person);
I would recommend you to define a standard date format in order to easily grab all the persons matching the search criteria.
Please forgive me for using vb.net syntax here as I am more acustomed to it. The translation should be quite straightforward though:
Dim rdr As New IO.StreamReader("filename.txt")
While rdr.Peek <> -1
Dim strLine as String = rdr.ReadLine()
If strLine.Contains("Birth Month,11") Then
Label6.Text &= strLine
End If
End While
rdr.Close()
Hope that helps.

Categories