how to show the checked checkbox into a messagebox in C# - c#

I was wondering how to do like the below image:
In 'Summary' (on right), under 'You purchased:', I want to list the options user has checked in 'Available Books' (on left)
private void btnPurchase_Click(object sender, EventArgs e)
{
string BOOKS;
MessageBox.Show("You Purchase :\n"
+"\t" + BOOKS + "\n" //checked checkbox shows here
+ "The selected payment method is : " + payment
+ "\nYour comment about us : " + txtKomen.Text);
}
I use the code above, and it only show the first checked checkbox, how to add another checked checkbox in message box?
Should I use an array for the BOOKS? If that is the way, how to loop it into the messagebox?

You can do it like this:
private void btnPurchase_Click(object sender, EventArgs e)
{
string[] BOOKS;
var sb = new StringBuilder();
foreach(var item in BOOKS)
{
sb.Append($"\t{item}");
sb.AppendNewLine();
}
MessageBox.Show("You Purchase :\n"
+ sb.ToString()//checked checkbox shows here
+ "The selected payment method is : " + payment
+ "\nYour comment about us : " + txtKomen.Text);
}
Though I'm not sure if .Append and .AppendNewLine() exist in StringBuilder, they might have a different name in any case Visual Studio should tell you the correct name.

private void button1_Click(object sender, EventArgs e)
{
string books = "";
foreach (var itemChecked in checkedListBox1.CheckedItems)
{
books += itemChecked + " ";
}
MessageBox.Show("You Purchase :\n" + "\t" + books + "\n");
}
If you want to use this you have to add CheckedListBox on your form.

Related

How to pass string value to another form's load event in C # [duplicate]

This question already has answers here:
How can we pass data from one opened form to another?
(2 answers)
Closed 5 years ago.
(I'm currently taking c#, but I've never taken any of the prerequisite classes, so please forgive my limited understanding.)
The answers I've seen so far aren't what I need for this project.
This is what I have so far:
//Form1
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
string strStatus = "";
if (rdoMarr.Checked)
{
strStatus = "Married";
}
else
{
strStatus = "Single";
}
string strPrint = "Marital Status = " + strStatus + "\n Pay Period =" + cbPayPd.Text + "\n Dependents =" + cbAllow.Text + "\n Gross = " + txtGross.Text + "\n Fit = " + txtFit.Text + "\n Soc = " + txtSoc.Text + "\n Med = " + txtMed.Text + "\n Net = " + txtNet.Text;
var form2 = new Print(strPrint);
form2.Show();
}
What needs to go onto my Form2 to receive this string?
There are many ways to do this. The one below is not what I would recommend, but I think it's the easiest to understand.
Here's one way to do this:
Create a public static property on your Form1 class to hold the value of this variable
Use the property from step #1 for the MessageBox text
Create a method that will update this property with the text you want
Call the method in #3 when your form loads
Create a common EventHandler method that calls the method in #2
Hook up the TextChanged event of the TextBox objects whose text is used in your string to the common EventHandler created in #4
Reference the property in #2 when your Form2 loads
My example assumes you have a Label named label1 on the Form that you want to update with the text
Here's how:
public partial class Form1 : Form
{
// 1. This class-level variable will hold our string
public static string PrintMessage { get; private set; }
// 2. Reference your strPrint variable for the MessageBox as you were before
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show(PrintMessage);
}
// 3. This method will update our string with values from TextBoxes
private void UpdateText()
{
PrintMessage = "Gross = " + txtGross.Text + "\n Fit = " + txtFit.Text +
"\n Soc = " + txtSoc.Text + "\n Med = " + txtMed.Text +
"\n Net = " + txtNet.Text;
}
// 4. Call our update method when the Form loads
private void Form1_Load(object sender, EventArgs e)
{
UpdateText();
}
// 5. This EventHandler just calls our update method
private void CommonTextChangedEvent(object sender, EventArgs e)
{
UpdateText();
}
// I have a `button1` on my Form1, and clicking this button shows Form2
private void button1_Click(object sender, EventArgs e)
{
var form2 = new Form2();
form2.Show();
}
Now, hook up the event handler. The easiest way is:
One at a time, select one of the textboxes whose Text is used in our string
In the Properties window, click the Events button (looks like a lightning bolt)
Choose the TextChanged event, and assign our new method to it
Now, in your Form2 class, you should be able to reference the Form1 property you created in #1:
public partial class Form2 : Form
{
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = Form1.PrintMessage;
}
To test it, just run the project, change the text in the text boxes, and click the button to load Form2

Add multiple items into array and display array in textbox

I currently have a form which takes in 3 user inputs from 2 textboxes and 1 numericUpDown.
I want to be able to get the values put in here when a button is clicked, and display the value of all 3 into a seperate text box.
The issue arises when there is multiple additions.
I tried creating an array but it still only displays the last input.
private void AddButton_Click(object sender, EventArgs e)
{
string newItem = NameTextBox.Text + "\t" + QuantityBox.Value.ToString() + "\t" + PriceBox.Text;
List<String> newItemList = new List<string>();
newItemList.Add(newItem);
for(int i = 0; i < newItemList.Count; i++)
{
BasketBox.Text = newItemList[i] + "\n";
}
}
Make your list outside the function, so u can maintain the list of inputs,
and display updated list on every click.
List<String> newItemList = new List<string>();
private void AddButton_Click(object sender, EventArgs e)
{
string newItem = NameTextBox.Text + "\t" + QuantityBox.Value.ToString() + "\t" + PriceBox.Text;
newItemList.Add(newItem);
for(int i = 0; i < newItemList.Count; i++)
{
BasketBox.Text = newItemList[i] + "\n";
}
}
You can do it like this:
private void AddButton_Click(object sender, EventArgs e)
{
string newItem = NameTextBox.Text + "\t" + QuantityBox.Value.ToString() + "\t" + PriceBox.Text;
List<String> newItemList = new List<string>();
newItemList.Add(newItem);
for(int i = 0; i < newItemList.Count; i++)
{
BasketBox.Text += newItemList[i] + "\n"; // this will add the text to your box
}
}
This will 'erase' old text in BasketBox:
BasketBox.Text = newItemList[i] + "\n"
This will add text in BasketBox:
BasketBox.Text += newItemList[i] + "\n"
There is a cool method String.Join which does the concatenation of string items from a list in one blow:
BasketBox.Text = String.Join(Environment.NewLine, newItemList);
If you declare the list outside than each time the button is clicked an item will be added to it and all items will be displayed:
List<String> newItemList = new List<string>();
private void AddButton_Click(object sender, EventArgs e)
{
string newItem = NameTextBox.Text + "\t" + QuantityBox.Value.ToString() + "\t" + PriceBox.Text;
newItemList.Add(newItem);
BasketBox.Text = String.Join(Environment.NewLine, newItemList);
}
Edit:
This of course will only work if you have set the property Multiline to true.

Textbox value in other textbox by clicking button not correct

This program have a link which is fixed and never change. And it contains 5 textboxes. The fixed link is:
<seite>utm_source=<website>_<page>_de&utm_medium=banner&utm_campaign=<kampagne>&utm_content=<format>
Every value in <> should be changed by textbox value. Here you got an image of my little program:
Now my problem is: the first value is correct, but the other values aren't. So for example, if i type in second texbox: "website" it does not only replace <website> with "website". it replaced <website> with System.Windows.Forms.TextBox, Text: website.
My Code I tried:
private void btn_SendAll_Click(object sender, EventArgs e)
{
txt_FinishLink.Text = txt_Site.Text + "utm_source=" + txt_Website + "_" + txt_Page + "_de&utm_medium=banner&utm_campaign=" + txt_Campaign + "&utm_content=" + txt_Format;
}
As pointed out in the comments, the Text property of the TextBox needed to be used:
txt_FinishLink.Text = txt_Site.Text + "utm_source=" + txt_Website.Text + "_" + txt_Page.Text + "_de&utm_medium=banner&utm_campaign=" + txt_Campaign.Text + "&utm_content=" + txt_Format.Text
Text will return the string of characters in the specified TextBox.
private void btn_SendAll_Click(object sender, EventArgs e)
{
txt_FinishLink.Text = txt_Site.Text + "utm_source=" +
txt_Website.Text + "_" +
txt_Page.Text + "_de&utm_medium=banner&utm_campaign=" +
txt_Campaign.Text + "&utm_content=" +
txt_Format.Text;
}
Look at string.Format though, it makes it much easier to see the format of the new url:
private void btn_SendAll_Click(object sender, EventArgs e)
{
txt_FinishLink.Text = string.Format(
"{0}utm_source={1}_{2}_de&utm_medium=banner&utm_campaign={3}&utm_content={4}",
txt_Site.Text, //{0}
txt_Website.Text, //{1} etc.
txt_Page.Text,
txt_Campaign.Text,
txt_Format.Text);
}
Then you may want to consider encoding the text before placing in the URL, see this answer https://stackoverflow.com/a/16894322/360211

Public override string toString, ArrayList and Listbox output in multiplelines?

I've been struggling with this C# problem all night.
I have a override ToString(), which is working fine, and I can put my data out in a ListBox. But as the data is very long, with a bunch of classes, the output becomes long.
I wanted to be able to break my ListBox output into multiplelines.
Here is the override in the class file:
//ToString
public override string ToString()
{
return "Name " + firstName + lastName + ". Nationality " + nationality + ". Lives in " + address + " " + zipCode + " " + city + " " + country + "."//
+ " Height is " + height + " meters. Hair color is " + hairColor + " and eye color is " + eyeColor + ". Specialmarkings: "//
+ specialMark + ". Is associated with " + association + ". Codename is " + codeName + "Photo (filename): " + photo;
}
Here is the index code:
public partial class Index : System.Web.UI.Page
{
static ArrayList personarraylist;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
personarraylist = new ArrayList();
}
}
protected void ButtonCreate_Click(object sender, EventArgs e)
{
//create new object
Person p = new Person(TextBox1FirstName.Text, TextBox2LastName.Text, TextBox3Nation.Text, TextBox4Address.Text, //
TextBox5City.Text, TextBox7Country.Text, //
TextBox10HairColor.Text, TextBox11EyeColor.Text, TextBox12SpecialMark.Text, TextBox13Asso.Text, TextBox14Codename.Text, TextBox15Photo.Text, //
Convert.ToDouble(TextBox9Height.Text), Convert.ToInt32(TextBox6ZipCode.Text), Convert.ToInt32(TextBox8Pass.Text));
//add object to arraylist
personarraylist.Add(p);
}
protected void ButtonShow_Click(object sender, EventArgs e)
{
//clear list box
ListBox1.Items.Clear();
//loop through Arraylist
for (int i = 0; i < personarraylist.Count; i++)
{
ListBox1.Items.Add(personarraylist[i].ToString());
ListBox1.Items.Add("");
TextBox1.Text = "";
}
}
}
Is it possible to break the output in multiplelines in a ListBox?
I was trying to inject some html breaktags in the override return, but these get stripped, yeah this is a webapplication.
Thanks in advance for your time.
PS I am a newbie in C# (Student), so be kind ;)
UPDATE:
Hi again all, thx for the help, I already tried with Environment.Newline and the other solutions, but these seem to be overlooked when displaying the text in a ListBox. I can see the breakpoints in the codebehind, but in the browser the listbox still just keeps it all in one line. So I decided to use a TextBox instead, which breaks the text automaticly and where I point out.
//loop through Arraylist
for (int i = 0; i < personarraylist.Count; i++)
{
TextBox1.Text += personarraylist[i].ToString();
}
Again thx for the help :-)
You can use Environment.NewLine or simply "\n" to create multiple lines of text.
If that doesn't work, you can try using the DataList control:
<asp:DataList id="myDataList" runat="server">
<ItemTemplate>
Line 1
<br />
Line 2
</ItemTemplate>
</asp:DataList>

How to make a radio button selection from groupbox appear in a label?

Is there a way when a user selects a choice from a radio button from a group-box to appear in a label?
It would be on the line with Quantity/Phone Type right after numberPhoneTextBox.Text.
There are a total of 3 radio-buttons for the user to choose from.
private void displayButton_Click(object sender, EventArgs e)
{
summaryLabel.Text = "Receipt Summary\n" +
"--------------\n" +
"Name: " + nameTextBox.Text +
"\nAddress: " + streetTextBox.Text +
"\nCity: " + cityTextBox.Text +
"\nState: " + stateTextBox.Text +
"\nZip Code: " + zipTextBox.Text +
"\nPhone Number: " + phoneNumberTextBox.Text +
"\nDate: " + dateMaskedBox.Text +
"\n-------------------------" +
"\nQuantity/Phone Type: " + numberPhoneTextBox.Text + "/";
}
You would have to do it by hand, unfortunately. You could define a method or property that performs the task for you to avoid repetitive code, like so:
String GetRadioButtonValue() {
if( radioButton1.Checked ) return radioButton1.Text;
else if( radioButton2.Checked ) return radioButton2.Text;
else return radioButton3.Text;
}
UPDATE:
Apparently the OP's assignment "doesn't allow the user of if/else statements" - that's quite surreal, but you can skirt it several ways, such as using the ?: operator:
String GetRadioButtonValue() {
return radioButton1.Checked ? radioButton1.Text
: radioButton2.Checked ? radioButton2.Text
: radioButton3.Text;
}
Another option is to use events:
private String _selectedRadioText;
public MyForm() { // your form's constructor
InitializeComponent();
radioButton1.CheckedChanged += RadioButtonCheckedChanged;
radioButton2.CheckedChanged += RadioButtonCheckedChanged;
radioButton3.CheckedChanged += RadioButtonCheckedChanged;
// or even:
// foreach(Control c in this.groupBox.Controls)
// if( c is RadioButton )
// ((RadioButton)c).CheckedChanged += RadioButtonCheckedChanged;
// Initialize the field
_selectedRadioText = radioButton1.Text;
}
private void RadioButtonCheckedChanged(Object sender, EventArgs e) {
_selectedRadioText = ((RadioButton)sender).Text;
}
// then just concatenate the _selectedRadioText field into your string
BTW, you should get out of the habit of using string concatenation. It's very inefficient. Instead, try something like this:
private void displayButton_Click(object sender, EventArgs e)
{
summaryLabel.Text =
string.Format(
"Receipt Summary\n--------------\nName: {0}\nAddress: {1}\nCity: {2}\nState: {3}\nZip Code: {4}\nPhone Number: {5}\nDate: {6}\n-------------------------\nQuantity/Phone Type: {7}/",
nameTextBox.Text,
streetTextBox.Text,
cityTextBox.Text,
stateTextBox.Text,
zipTextBox.Text,
phoneNumberTextBox.Text,
dateMaskedBox.Text,
numberPhoneTextBox.Text);
}

Categories

Resources