Getting CheckBoxList Item values - c#

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.

Related

Windows form - Make array to stop when there is no more data

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

How to modify an item inside ListBox?

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.

How to make a listbox item not duplicate itself to the next line of the listbox in C#

so I am adding an item in a listbox by clicking an image.
If the item gets clicked or added multiple times,it duplicates itself to the next line of the listbox. What I want is the item to have a counter that will count the number of instance it was clicked.
here's my code so far:
int ctr = 1;
private void item_img1_Click(object sender, EventArgs e)
{
if (!orderList.Items.Contains(item1.Text))
{
orderList.Items.Add(item1.Text + ctr);
ctr++;
}
}
Note that you're not actually adding item1.Text; you're adding item1.Text + ctr. That's why your if clause isn't keeping you from adding duplicates.
Use this code:
class ItemWrapper
{
public object item;
public string text;
public int ctr = 1;
public override string ToString()
{
return text + " (" + ctr + ")";
}
}
private void item_img1_Click(object sender, EventArgs e)
{
bool found = false;
foreach (var itm in orderList.Items)
if ((itm as ItemWrapper).text == item1.Text)
{
(itm as ItemWrapper).ctr++;
found = true;
break;
}
if (!found)
orderList.Items.Add(new ItemWrapper() { item = item1, text = item1.Text, ctr = 1 });
}
Where ItemWrapper is wrapper of your item object and overriding ToString() method in it allows listBox to display object as your defined format.

Add item in listview

I want to add item into the listview, the problem I'm facing is that when I add an item that I type in on the text box. It is able to insert the value in the listview column that I want. But when it update, all the data that it loaded from the textfile is missing. Only the value that I type in is left.
Before add data:
http://www.hostpic.org/images/1508121529460086.png
After insert the data:
http://www.hostpic.org/images/1508121531010086.png
private void button2_Click(object sender, EventArgs e)
{
//add button
string s;
listView1.Items.Clear();
listView1.BeginUpdate();
for (int i = 0; i < comboBox1.Items.Count; i++)
{
if ((comboBox1.SelectedIndex + 1) + "" == proDetail[i].id)
{
//proDetail[i].estimation = double.Parse(textBox3.Text);
proDetail[i].estimation = textBox3.Text;
s = textBox4.Text;
proDetail[i].pre = s.Split(',');
}
}
for (int j = 0; j < comboBox1.Items.Count; j++)
{
if (proDetail[j].pre != null)
{
project = listView1.Items.Add(proDetail[j].id);
project.SubItems.Add(proDetail[j].activity);
if (proDetail[j].pre.Length <= 1)
{
foreach (string words in proDetail[j].pre)
{
preValue = words;
}
}
else
{
preValue = string.Empty;
foreach (string words in proDetail[j].pre)
{
preValue += words + ",";
}
}
project.SubItems.Add(proDetail[j].estimation.ToString());
project.SubItems.Add(preValue);
}
else
{
project = listView1.Items.Add(proDetail[j].id);
project.SubItems.Add(proDetail[j].activity);
}
listView1.EndUpdate();
listView1.Refresh();
}
}
I forgot to include the
project.SubItems.Add(proDetail[j].estimation);
in the else statement.
Thanks for the help.
This is the culprit:
listView1.Items.Clear();
That has removed all existing items from the control.

How to display array elements, if the number of elements is a variable

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

Categories

Resources