i want to concat(add) a string over an existing item here is the code:
private void button4_Click(object sender, EventArgs e)
{
double total = 0;
double[] prices = {0.5, 1.0, 1.5, 3.0, 2.5, 2.0};
CheckBox[] boxes = { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6 };
listBox2.Items.Add(textBox1.Text + " : ");
for (int i=0;i<boxes.Length ;i++)
{
if (boxes[i].Checked==true)
{
total += prices[i];
listBox2.Items.Add(boxes[i].Text+" "); //it adds a new item
}
}
the problem is with the output , every time it adds a new item i just want to add this line boxes[i].Text+" " , to the same item
thank you.
What do you mean by:
to the same item
Do you want to add it all to this one? listBox2.Items.Add(textBox1.Text + " : ");
If so could you not just do this:
string name = textBox1.Text + " : ";
for (int i=0; i < boxes.Length; i++)
{
if (boxes[i].Checked == true)
{
total += prices[i];
name += boxes[i].Text + " ";
}
}
listBox2.Items.Add(name);
You should use the following command listbox2.items[0]+=boxes[i].Text+" " with 0 being the index of the item you want to concatenate the string with.Because listbox2.items.Add will just keep adding items to your Listbox.
Best Regards.
Related
Hello guys I am new to coding, and new to arrays as well and I was wondering how can I make this code to stop when there is no more names in the array, and from stop saying the number 10 always before the names. As well to show the position of the names one number above, not just starting from 0, but from 1.
Here is what I have so far.
string[] list = new string[10];
int pos = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string StudentName;
StudentName = textBox1.Text;
list[pos] = StudentName;
pos++;
textBox1.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(list.GetLength(0).ToString());
string message;
for (int i = 0; i < lista.GetLength(0); i++)
{
message = "";
message = "The student" + " " + list[i] + " has the position " + i ;
MessageBox.Show(message);
}
}
Use a dynamic array, aka List<T>
List<string> list = new List<string>();
Instead of manually keeping track of the position, just add the item to the end:
list.Add(StudentName);
You can check the number of current items in the list by using .Count.
for (int i = 0; i < list.Count; i++) {...}
But you can also use a foreach loop to iterate over all the items in the list, but this way you do not get the position automatically.
foreach(var item in list){...}
For the sake of completeness, another way would be to filter out empty entries.
Linq is especially great for working with Enumerables like these:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where?view=net-6.0
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string[] list = new string[10];
list[0] = "test1";
list[1] = "test2";
for (var index = 0; index < list.Length; index++)
{
var s = list[index];
Console.WriteLine($"[{index}] {s}");
}
// Filter out null, an empty string or only whitespace characters from the array
list = list
.Where(c => !string.IsNullOrWhiteSpace(c))
.ToArray();
Console.WriteLine("==========================");
for (var index = 0; index < list.Length; index++)
{
var s = list[index];
Console.WriteLine($"[{index}] {s}");
}
}
}
https://dotnetfiddle.net/g7e0Nm
First you can specify the maximum capacity of your array using a const
const int arrayCapacity = 10;
string[] list = new string[arrayCapacity];
int pos = 0;
Then you should add some validation if the array is full, according to your maximum capacity, and/or if the textbox is empty.
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Textbox was empty");
return;
}
if (pos > arrayCapacity - 1)
{
MessageBox.Show("Array is full");
textBox1.Clear();
return;
}
list[pos] = textBox1.Text;
pos++;
textBox1.Clear();
}
And the last step is to create a new array in any case you have a smaller number of students than your initial array's capacity
private void button2_Click(object sender, EventArgs e)
{
var arr = list.Where(x => !string.IsNullOrEmpty(x)).ToArray();
for (int i = 0; i < arr.Length; i++)
{
string message = "The student" + " " + arr[i] + " has the position " + (i + 1);
MessageBox.Show(message);
}
}
When the Add button is pressed the price is taken from the second half of a 'split' line in the first list box. This is then multiplied by a value entered in a textbox or just entered as is into the second listbox.
I have then added a line below it in the second list box with the total price. When a new item is added the code removes the previous total price and replaces it with the new updated total price.
I'm looking to then append (add all the prices being listed in the second listbox) the prices together in the 'total price' section of the last line of the second list box.
Below is the code I have written so far.
private void button1_Click(object sender, EventArgs e)
{
string TheItem = Convert.ToString(listBox1.SelectedItem);
string[] theSplits = TheItem.Split(' ');
string FirstSplit = theSplits[0];
string SecondSplit = theSplits[1];
Decimal theNewTotal;
Decimal theValue;
if (textBox1.Text == "")
{
listBox2.Items.Add(TheItem);
listBox2.Items.Add("Total Price:" + SecondSplit);
}
else
{
theValue = Convert.ToDecimal(SecondSplit) * Convert.ToDecimal(textBox1.Text);
listBox2.Items.Add(textBox1.Text + "x " + TheItem);
theNewTotal = theValue;
listBox2.Items.Add("Total Price:" + theNewTotal);
}
if (listBox2.Items.Count > 2)
{
int theNumber = listBox2.Items.Count;
listBox2.Items.RemoveAt(theNumber-3);
}
}
You'd be better off starting by removing the total price first, as you expend some effort trying to work around that. So something like:
private void button1_Click(object sender, EventArgs e) {
RemoveLastTotal();
AppendPrices();
AppendTotal();
}
private void RemoveLastTotal() {
var lastItemIndex = listBox2.Items.Count-1;
if (listBox2.Items[lastItemIndex].StartsWith("Total Price:"))
{
listBox2.Items.RemoveAt(lastItemIndex);
}
}
private void AppendPrices() {
string TheItem = Convert.ToString(listBox1.SelectedItem);
string[] theSplits = TheItem.Split(' ');
string itemDesc = theSplits[0];
string itemPrice = theSplits[1];
float quantity = (string.IsNullOrEmpty(textBox1.Text))? 0: float.Parse(textBox1.Text)
if (quantity==0) {
listBox2.Items.Add(TheItem);
} else {
var lineTotal = Convert.ToDecimal(itemPrice) * quantity;
listBox2.Items.Add(textBox1.Text + " x " + TheItem + " = " + lineTotal);
}
}
private void AppendTotal()
{
var total = 0;
foreach(var item in listBox2.Items)
{
var splits = item.Split(' ');
total += decimal.parse(splits[splits.length-1]);
}
listBox2.Items.Add("Total Price:" + total);
}
That said, if you really want to do it "properly", you should separate the view i.e. the listbox from the model (DataTable for instance).
I'm making a calculator in GUI, and I need some help.
When I enter some data in a text box, I need to store it in an array. This is how I thought of it.
int numOfPackages;//used to get user input
private void button3_Click(object sender, EventArgs e)
{
int[] weight = new int[numOfPackages];
for(int i = 0; i < numOfPackages; i++)
{
weight[i] = Convert.ToInt32(weightBox.Text);
}
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
}
And when I try to display the elements, it gives me the indexOutOfRange exception.
So, how do I display the elements of that array?
Thanks in advance.
This line
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
should be
foreach (int w in weight)
totalCostLabel.Text = "" + w;
Your current code iterates the array of weights, and tries to use the weight as an index into the array of weights, causing an index out of range exception.
Another problem is with the first loop: you are setting all values of weight to the same number:
weight[i] = Convert.ToInt32(weightBox.Text); // That's the same for all i-s
If weights are to be different, they should come from different weight boxes, or the string from a single weightBox should be processed in such a way as to produce multiple numbers (for example, by using string.Split).
You have multiple problems here. First is this:
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
This is iterating the weight array and using each value in that array. You then use that value as an index. Take the following example:
weight[0] = 0
weight[1] = 1
weight[2] = 15
In your code, the first two entries will work because there is an index of 0 and an index of 1. But when it gets to the last entry, it looks for an index of 15. You can fix this two ways, the first is to use a regular for loop:
for(int i=0; i < weight.Length; i++)
{
totalCostLabel.Text += weight[i];
}
This brings the second mistake. You aren't appending anything to your totalCostLabel in your code, you are just replacing the value. This will append all the values of weight together as one.
Another way to do this is to use the foreach loop:
foreach(int i in weight)
{
totalCostLabel.Text += i;
}
This is the same as above but you don't have to worry about indexing.
Bottom line, even after you fix your loop, you will probably need to fix the way that the label takes the text otherwise you won't get your desired result.
Maybe you wanted something more like?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
btnAdd.Enabled = false;
}
int[] weight;
int entriesMade;
int numOfPackages;
private void btnReset_Click(object sender, EventArgs e)
{
if (int.TryParse(numEntriesBox.Text, out numOfPackages))
{
weight = new int[numOfPackages];
entriesMade = 0;
btnReset.Enabled = false;
btnAdd.Enabled = true;
totalCostLabel.Text = "";
}
else
{
MessageBox.Show("Invalid Number of Entries");
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
int value;
if (int.TryParse(weightBox.Text, out value))
{
weight[entriesMade] = value;
weightBox.Clear();
totalCostLabel.Text = "";
int total = 0;
for (int i = 0; i <= entriesMade; i++)
{
total = total + weight[i];
if (i == 0)
{
totalCostLabel.Text = weight[i].ToString();
}
else
{
totalCostLabel.Text += " + " + weight[i].ToString();
}
}
totalCostLabel.Text += " = " + total.ToString();
entriesMade++;
if (entriesMade == numOfPackages)
{
btnAdd.Enabled = false;
btnReset.Enabled = true;
MessageBox.Show("Done!");
}
}
else
{
MessageBox.Show("Invalid Weight");
}
}
}
Before I had a question about (specific distance (space) between columns of drop down list) and I received my answer like below code, my problem is the spaces between columns will be fill by '_', when I change that to something like " ", it does not work and columns are beside each other, I need white space between columns, how can I do that?
protected void ddlStack_Load(object sender, EventArgs e)
{
var all = from o in _DataContext.tblDocuments
orderby o.DocumentNo
select o;
int maxs = 0;
foreach (tblDocuments v in all)
{
if (v.DocumentNo.Length > maxs)
maxs = v.DocumentNo.Length;
}
foreach (tblDocuments vv in all)
{
string doctitle = vv.DocumentNo;
for (int i = vv.DocumentNo.Length; i < maxs + 2; i++)
{
doctitle += '_';
}
doctitle += " | ";
doctitle += vv.DocID;
ddlStack.Items.Add(new ListItem(doctitle, vv.vendorID.ToString()));
}
}
You should use instead of a regular " " (space) and then use HtmlDecode before creating the ListBoxItem...
Try something like this:
foreach (tblDocuments vv in all)
{
string doctitle = vv.DocumentNo;
for (int i = vv.DocumentNo.Length; i < maxs + 2; i++)
{
doctitle += " ";
}
doctitle += " | ";
doctitle += vv.DocID;
// Use HtmlDecode to correctly show the spaces
doctitle = HttpUtility.HtmlDecode(doctitle );
ddlStack.Items.Add(new ListItem(doctitle, vv.vendorID.ToString()));
}
I have a CheckBoxList which I'm populating with data. When I attempt to retrieve the checked items from the list I can only grab the item ordinal, I cannot get the value.
I've read that you can use Items[i].Value however when I try to do this I get an error stating that there is no extension method 'value'.
Here's the code I'm using to try and grab the information (note the GetItemText(i) actually only gives me the item position, not the text for the item)
private void btnGO_Click(object sender, EventArgs e)
{
for (int i = 0; i < chBoxListTables.Items.Count; i++)
{
if (chBoxListTables.GetItemChecked(i))
{
string str = chBoxListTables.GetItemText(i);
MessageBox.Show(str);
//next line invalid extension method
chBoxListTables.Items[i].value;
}
}
}
This is using .Net 4.0
Any thoughts would be appreciated...thanks
This ended up being quite simple. chBoxListTables.Item[i] is a string value, and an explicit convert allowed it to be loaded into a variable.
The following code works:
private void btnGO_Click(object sender, EventArgs e)
{
for (int i = 0; i < chBoxListTables.Items.Count; i++)
{
if (chBoxListTables.GetItemChecked(i))
{
string str = (string)chBoxListTables.Items[i];
MessageBox.Show(str);
}
}
}
Try to use this.
for (int i = 0; i < chBoxListTables.Items.Count; i++)
{
if (chBoxListTables.Items[i].Selected)
{
string str = chBoxListTables.Items[i].Text;
MessageBox.Show(str);
var itemValue = chBoxListTables.Items[i].Value;
}
}
The "V" should be in CAPS in Value.
Here is another code example used in WinForm app and runs properly.
var chBoxList= new CheckedListBox();
chBoxList.Items.Add(new ListItem("One", "1"));
chBoxList.Items.Add(new ListItem("Two", "2"));
chBoxList.SetItemChecked(1, true);
var checkedItems = chBoxList.CheckedItems;
var chkText = ((ListItem)checkedItems[0]).Text;
var chkValue = ((ListItem)checkedItems[0]).Value;
MessageBox.Show(chkText);
MessageBox.Show(chkValue);
to get the items checked you can use CheckedItems or GetItemsChecked. I tried below code in .NET 4.5
Iterate through the CheckedItems collection. This will give you the item number in the list of checked items, not the overall list. So if the first item in the list is not checked and the second item is checked, the code below will display text like Checked Item 1 = MyListItem2.
//Determine if there are any items checked.
if(chBoxListTables.CheckedItems.Count != 0)
{
//looped through all checked items and show results.
string s = "";
for (int x = 0; x < chBoxListTables.CheckedItems.Count; x++)
{
s = s + (x + 1).ToString() + " = " + chBoxListTables.CheckedItems[x].ToString()+ ", ";
}
MessageBox.Show(s);//show result
}
-OR-
Step through the Items collection and call the GetItemChecked method for each item. This will give you the item number in the overall list, so if the first item in the list is not checked and the second item is checked, it will display something like Item 2 = MyListItem2.
int i;
string s;
s = "Checked items:\n" ;
for (i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemChecked(i))
{
s = s + "Item " + (i+1).ToString() + " = " + checkedListBox1.Items[i].ToString() + "\n";
}
}
MessageBox.Show (s);
Hope this helps...
//Simple example code:
foreach (var item in YourCheckedListBox.CheckedItems)
{List<string>.Add(item);}
You can try this:-
string values = "";
foreach(ListItem item in myCBL.Items){
if(item.Selected)
{
values += item.Value.ToString() + ",";
}
}
values = values.TrimEnd(','); //To eliminate comma in last.
Instead of this:
CheckboxList1.Items[i].value;
Try This:
CheckboxList1.Items[i].ToString();
It worked for me :)
Try to use this :
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < chBoxListTables.Items.Count; i++)
if (chBoxListTables.GetItemCheckState(i) == CheckState.Checked)
{
txtBx.text += chBoxListTables.Items[i].ToString() + " \n";
}
}
You can initialize a list of string and add those items that are selected.
Please check code, works fine for me.
List<string> modules = new List<string>();
foreach(ListItem s in chk_modules.Items)
{
if (s.Selected)
{
modules.Add(s.Value);
}
}
This will do the trick for you:
foreach (int indexChecked in checkedListBox1.CheckedIndices)
{
string itemtxt = checkedListBox11.Items[indexChecked];
}
It will return whatever string value is in the checkedlistbox items.