Invalid argument value of '1' is not valid for 'index' - c#

I have a listview and I want when a button is pressed to delete the selected item. Additionally, I use the item for some other actions. Basically, I use some letters of the item' s string to match with a file and delete it. This works if the selected item is the first one in the listview, but doesn' t work if it's second, third etc.
private void delete_button_Click(object sender, EventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected)
{
string var1 = listView1.SelectedItems[i].ToString(); //error
string var2 = var1.Substring(31, 5);
... // code for other actions
listView1.Items[i].Remove();
i--;
}
}
}
It thorws error
ArgumentOutofRangeException was not handled" - Invalid argument value
of '1' is not valid for 'index'
I don't understand what's the problem and why it works only if it' s the first item.

Selected items contains only those selected, and yet you are iterating over the entire collection.
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected)
{
string var1 = listView1.Items[i].ToString(); // <-------
string var2 = var1.Substring(31, 5);
... // code for other actions
listView1.Items[i].Remove();
i--;
}
}

I think the problem is, that your index increases while listView1.Items is getting smaller.

You check for Items to start with but then check the index against SelectedItems
If there are 4 elements in Items and only the 4th is selected then SelectedItems has 1 item but i would be 4
for (int i = 0; i < listView1.SelectedItems.Count; i++)
{
string var1 = listView1.SelectedItems[i].ToString();
string var2 = var1.Substring(31, 5);
... // code for other actions
listView1.Items[i].Remove();
i--;
}
}

var1 needs to be from Items, not from SelectedItems. Like this:
private void delete_button_Click(object sender, EventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected)
{
string var1 = listView1.Items[i].ToString(); //NOTE THE DIFFERENCE
string var2 = var1.Substring(31, 5);
... // code for other actions
listView1.Items[i].Remove();
i--;
}
}
In fact though, a better way to do this would be like this:
private void delete_button_Click(object sender, EventArgs e)
{
foreach (var x in listView1.SelectedItems.Select(x => x))
listView1.Items.Remove(x);
}

This is because you are iterating through the items in the list box, and not the selected items. For example if you have 10 items in the box, and you have selected 2, when it gets to the thrird iteration it will fail.

Use this one instead you code:
foreach(var item in listView.SelectedItems){ //todo }

if you have a collection with only the selected ones why are you iterating all the elements?
just do this.
foreach(var var1 in listView1.SelectedItems.ToArray())
//the to array is to create e new collection from the list else you get one error when you change it.
{
string var2 = var1.Substring(31, 5);
... // code for other actions
listView1.Items.Remove(var1);
}

Try this;
for (int i = listView1.Items.Count-1; i >=0 ; i--)
{
if (listView1.Items[i].Selected)
{
string var1 = listView1.SelectedItems[i].ToString(); //error
string var2 = var1.Substring(31, 5);
... // code for other actions
listView1.Items[i].Remove();
}
}

Related

how to get next row data in gridview?

i want to get next data in gridview, the thing is when i use break; it totally out of loop, but when i dont use break; it otomatically call the last row data of the text that i type.
private void button7_Click(object sender, EventArgs e)
{
for (int i = 0; i < gridView1.RowCount; i++)
{
var row = gridView1.GetDataRow(i);
var genre = row["genre"].ToString();
if (genre.IndexOf(textBox8.Text, StringComparison.OrdinalIgnoreCase) >= 0)
{
gridView1.FocusedRowHandle = i;
break;
}
}
}
if i dont use break it will select the last data with 'ba' = basketball.
what i want is when i click next it select ballet and stop, and when i click next button again it select basketball
use an int variable to store the current iteration of loop:
int iteration=0;
private void button7_Click(object sender, EventArgs e)
{
for (int i = iteration; i < gridView1.RowCount; i++)
{
var row = gridView1.GetDataRow(i);
var genre = row["genre"].ToString();
if (genre.IndexOf(textBox8.Text, StringComparison.OrdinalIgnoreCase) >= 0)
{
gridView1.FocusedRowHandle = i;
iteration=i+1;
break;
}
}
}
And on Find button you can reset iteration to 0

How can I find the sum of the elements within a ListBox in WPF

How can I find the sum of the elements within a ListBox. I just need to find a way to store the sum of the values of the ListBox and output once the users inserts the wrong input
private void theMethod(object sender, RoutedEventArgs e)
{
// YesButton Clicked! Let's hide our InputBox and handle the input text.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
// Do something with the Input
String input = InputTextBox.Text;
int result = 0;
if (int.TryParse(input, out result))
{
MyListBox.Items.Add(result); // Add Input to our ListBox.
}
else {
String[]arr = new String[3];
// I just want to be able to output the sum of the elements of the ListBox (MyListBox)
for ( i = 0; i < MyListBox.Items.Count; i++)
{
//MyListBox.Items[i].ToString();
MyListBox.Items.Cast<ListBoxItem>().Sum(x => Convert.ToInt32(x)).ToString();
}
sum.ToString();
MessageBox.Show("Sum is: " +MyListBox.Items.Cast<ListBoxItem>().Sum(x => Convert.ToInt32(x)).ToString());
}
The problem of your code is here:
MyListBox.Items.Cast<ListBoxItem>
To calculate sum of items of your list box, if you are sure that they are integer numbers that added as int or string, you can use this snippet:
var sum= this.ListBox1.Items.Cast<object>()
.Select(x => Convert.ToInt32(x))
.Sum();
MessageBox.Show(sum.ToString());
The above code assumes that you add items to ListBox using such code:
var value= this.TextBox1.text;
//your logic for null checking and ...
this.ListBox1.Items.Add(value);
Here is the complete code that I test based on your codes.
While you are adding integer values to listbox, we don't need Cast<object> and Select(x=>Convert.ToInt32(x)) anymore and its enough to Cast<int> like below:
String input = InputTextBox.Text;
int result = 0;
if (int.TryParse(input, out result))
{
MyListBox.Items.Add(result);
}
else
{
var sum = this.MyListBox.Items.Cast<int>().Sum();
MessageBox.Show(string.Format("Sum is: {0}", sum));
sum.ToString();
}
InputTextBox.Text = String.Empty;
this worked for me , try this :
private void YesButton_Click(object sender, RoutedEventArgs e)
{
int sum = 0;
int i = 0;
// YesButton Clicked! Let's hide our InputBox and handle the input text.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
// Do something with the Input
String input = InputTextBox.Text;
int result = 0;
if (int.TryParse(input, out result))
{
MyListBox.Items.Add(result); // Add Input to our ListBox.
}
else
{
sum = MyListBox.Items.Cast<int>().Sum(x => Convert.ToInt32(x));
MessageBox.Show("Sum is: " +sum);
}
// Clear InputBox.
InputTextBox.Text = String.Empty;
}

Fill Data in Listbox with another Listbox which is having Data-Bound

I have this two list-box In that first list-box is fill on Combo-box Selected index changed, so List-box 1 is Bounded. Now when I press the > button all selected item in List-box 1 is display in List-box 2.
But instead of Names, I get System.Data.DataRowView
so my question is I want Names instead of this System.Data.DataRowView
my code is this
private void btnSelect1ItemFrom_Click(object sender, EventArgs e)
{
if (listBoxSelectToLedger.Items.Count > 0)
{
for (int i = 0; listBoxSelectToLedger.Items.Count > i; )
{
listBoxSelectToLedger.Items.Remove(listBoxSelectToLedger.Items[i].ToString());
}
}
if (listBoxSelectFromLedger.SelectedItem != null)
{
** for (int i = 0; i < listBoxSelectFromLedger.SelectedItems.Count; i++)
{
listBoxSelectToLedger.Items.Add(listBoxSelectFromLedger.SelectedItems[i].ToString());
} **
}
else
{
MessageBox.Show("No item Selected");
}
* I think I am some where Wrong in Second IF Condition in my Code *
Plz Help me
Thanks in Advance
Try this...
private void button1_Click(object sender, EventArgs e)
{
if(listBoxFrom.SelectedItems.Count>0)
{
for (int x = listBoxFrom.SelectedIndices.Count - 1; x >= 0; x--)
{
int idx = listBoxFrom.SelectedIndices[x];
listBoxTo.Items.Add(listBoxFrom.Items[idx]);
listBoxFrom.Items.RemoveAt(idx);
}
}
}
Hiii.. Deep, use the below code to add ListItem.
foreach (ListItem LI in listBoxFrom.Items)
{
if (LI.Selected)
listBoxTo.Items.Add(LI);
}
To add in to 2nd listbox and remove that from the first listbox you can use below code:
int[] indices = listBoxFrom.GetSelectedIndices();
for (int i = indices.Length - 1; i >= 0; i--)
{
ListItem LI = listBoxFrom.Items[indices[i]];
listBoxTo.Items.Add(LI);
listBoxFrom.Items.RemoveAt(indices[i]);
}
put your No items selected message where you require.
I got answer of my own question.
i have to set my DataRowView object
if (listBoxSelectToLedger.Items.Count > 0)
{
for (int i = 0; listBoxSelectToLedger.Items.Count > i; i = 0)
{
listBoxSelectToLedger.Items.Remove(listBoxSelectToLedger.Items[i].ToString());
}
}
if (listBoxSelectFromLedger.SelectedItem != null)
{
foreach (DataRowView objDataRowView in listBoxSelectFromLedger.SelectedItems)
{
listBoxSelectToLedger.Items.Add(objDataRowView["item_name"].ToString());
}
}
else
{
MessageBox.Show("No Item selected");
}

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

Getting CheckBoxList Item values

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.

Categories

Resources