listView.Selectedindeces[0] Unhandled exception - c#

I'm trying to locate the list item that a user selects in a ListView box, however, whenever I try to use listview.SelectedIndeces[0], I get an unhandled exception error stating "InvalidArgument=Value of '0' is not valid for "index"".
Here is the code:
private void TabPage3_Click(object sender, EventArgs e)
{
foreach (Child child in Children)
{
editChildListView.Items.Add(new ListViewItem(new string[] {child.name, child.dob.ToString("dd/MM/yy"), child.comment }));
}
if (editChildListView.Items.Count >= 0)
{
int selectedIndex = editChildListView.SelectedIndices[0];
editNameBox.Text = Children[selectedIndex].name;
}
}
ANSWER:
private void EditChildListView_SelectedIndexChanged(object sender, EventArgs e)
{
if (editChildListView.Items.Count >= 0)
{
int selectedIndex = editChildListView.SelectedIndices[0];
editNameBox.Text = Children[selectedIndex].name;
}
}
The method needed to be called from the listview_SelectedIndexChanged function rather than the tab3_Click function

If you do
int selectedIndex = editChildListView.SelectedIndices.FirstOrDefault();
Then you won't get an error if nothing is selected.
You probably just want to check something is selected.

Related

Looking to call method with parameter to take in specified text box

I am creating a Windows Form Application and I want to create a method to be able to pass in a specified text box from a _Click event. Such as below: My Method is AddTo() and I want to call from the 2 click events which have 2 separate text boxes. I want to be able to pass in the correct text box.
void AddTo(string ctrl)
{
int num= int.Parse(ctrl);
num++;
ctrl = num.ToString();
}
private void btnAddLevel_Click(object sender, EventArgs e)
{
AddTo(TextBox1.Text);
}
private void btnAddSecond_Click(object sender, EventArgs e)
{
AddTo(TextBox2.Text);
}
I am pretty new to C#, is this possible to do? Thanks in advance for any help.
UPDATE:
Here is the full code with the fix below
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
txtName.Text = "0";
}
void AddTo(ref TextBox tBox)
{
if (tBox.Text.Trim().Length > 0)
{
int num = 0;
//CHECK IF THE TEXT IS CONVERTIBLE TO NUMBER
if (int.TryParse(tBox.Text, out num))
{
num++;
tBox.Text = num.ToString();
}
}
}
private void btnAddUnit_Click(object sender, EventArgs e)
{
AddTo(ref txtName);
}
}
Use ref key word to retain data updates for passing objects.
Try below code:
//YOUR TEXTBOX IS A REFERNCE HERE. SO THAT THE UPDATES ARE RETAINED
void AddTo(ref TextBox tBox)
{
//VALIDATED YOUR TEXT BOX IF DATA EXISTS BEFORE UPDATING
if (tBox.Text.Trim().Length > 0 )
{
int num = 0;
//CHECK IF THE TEXT IS CONVERTIBLE TO NUMBER
if (int.TryParse(tBox.Text, out num))
{
num++;
tBox.Text = num.ToString();
}
}
}
While calling
//USE REF WHILE CALLING
AddTo(ref textBox1);//textbox object

Error: (using List class) Index was outside the bounds of array

I'm working on a project and I'm a beginner in programming in c#, and somehow there is a problem that I cannot solve. How it happened: In executing the code, the application launches successfully but an exception
shows that the "Index was outside the bounds of array". Afterwards, I was able to click items on a listbox and it shows the second object on the textbox. So... It seems like it works(clicking on listbox's item) but I cannot figure out why it would throw an exception about the array. Beneath is the current code that I have.
**Update:I sincerely apologize. I uploaded the wrong code. It is suppose to be this code:
Code:
struct studentInfo
{
public string studentID;
public string major;
}
public partial class Form1 : Form
{
private List<studentInfo> studentList = new List<studentInfo>();
public Form1()
{
InitializeComponent();
}
private void ReadInputFile()
{
try
{
StreamReader inputFile;
string line = "";
studentInfo student = new studentInfo();
char[] delimiter = { ',' };
inputFile = File.OpenText("Student Info.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] token = line.Split(delimiter);
student.studentID = token[0];
student.major = token[1];
studentList.Add(student);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void DisplaystudentID()
{
foreach (studentInfo student in studentList)
{
studentInfoListBox.Items.Add(student.studentID);
}
}
private void DisplayNames()
{
}
private void button1_Click(object sender, EventArgs e)
{
ReadInputFile();
DisplaystudentID();
}
private void studentInfoListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = studentInfoListBox.SelectedIndex;
majorTextBox.Text = studentList[index].major;
}
private void button3_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
My guess would be that SelectedIndexChanged is ran at the start (before you select anything) and at that point nameListBox.SelectedIndex would be -1 and you can't get the "negative 1 position's item" in a list. I would make sure that the selected index is valid
https://msdn.microsoft.com/fr-fr/library/system.windows.forms.listbox.selectedindex(v=vs.110).aspx
"A zero-based index of the currently selected item.A value of negative one (-1) is returned if no item is selected."
I would change the code as such:
private void nameListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = nameListBox.SelectedIndex;
if(index !=-1)
{
phoneLabel.Text = phoneList[index].phone;
}
// else do nothing, the selected item didn't really change, it's just called for the first time, think of it as the control saying "hey i just got created and i'm notifying you that the selected item is now nothing"
}
You have to guard SelectedIndex, when controls are initially created SelectedIndex is set to -1
private void nameListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if(nameListBox.SelectedIndex >=0)
{
int index = nameListBox.SelectedIndex;
phoneLabel.Text = phoneList[index].phone;
}
}
The only array handling you have in your program is this:
entry.name = tokens[0];
entry.phone = tokens[1];
Therefore the reason is that one of the lines in your text file does not have a comma, so tokens does not have 2 parts.
A common reason for this is simply having a file that has a linefeed after the final real entry, thereby having an empty line as the last line.
I would simply handle this here:
if (tokens.Length < 2)
continue;
You didn't let us know where exactly the exception is occurred but as I see it might be in this part
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
entry.name = tokens[0];
entry.phone = tokens[1];
If your line is empty or doesn't have "," you will get exception in the next line
Also you need to check the access to list in the index location in nameListBox_SelectedIndexChanged.
"Index was outside the bounds of array" exception occurs when you try to access an element which is not exits in the list. I believe you are getting this exception when you are click on the last item on your list.
In your nameListBox_SelectedIndexChanged method you one of following.
int index = nameListBox.SelectedIndex -1;
or
phoneLabel.Text = phoneList[index-1].phone;

Selecting Multiple Items From ListBox causes Collection was modified; enumeration operation may not execute

This is a simple code in which i am Transferring Items of one listBox to one Another on btnAdd_Click Event and btnRemove_Click Event resp.
This was working Fine when The selectionMode="Single" and at that point of time i had no need to use foreach inbtn_Add_Click. But Now i've changed selectionMode="Multiple" and used foreach in btnAdd_Click and when i am selecting multiple items from ListBox it is creating the following Error:-
Collection was modified; enumeration operation may not execute
class Movies
{
private Int32 _Id;
private string _movieName;
public Int32 Id
{
get { return _Id; }
set { _Id = value; }
}
public string movieName
{
get { return _movieName; }
set { _movieName = value; }
}
public Movies(Int32 ID, string MovieName)
{
Id = ID;
movieName = MovieName;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Movies> list = new List<Movies>();
list.Add(new Movies(1, "Movie1"));
list.Add(new Movies(2, "Movie2"));
list.Add(new Movies(3, "Movie3"));
list.Add(new Movies(4, "Movie4"));
list.Add(new Movies(5, "Movie5"));
list.Add(new Movies(6, "Movie6"));
list.Add(new Movies(7, "Movie7"));
lstMain.DataSource = list;
lstMain.DataBind();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
foreach (ListItem list in lstMain.Items)// Here the error comes
{
if(list.Selected)
{
lstFAvourite.ClearSelection();
lstFAvourite.Items.Add(list);
lstMain.Items.Remove(list);
}
}
}
protected void btnRemove_Click(object sender, EventArgs e)
{
ListItem list = lstFAvourite.SelectedItem;
lstMain.ClearSelection();
lstMain.Items.Add(list);
lstFAvourite.Items.Remove(list);
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (ListItem item in lstFAvourite.Items)
{
lbl1.Text += "<li>" + item.Text;
}
}
Please tell me what is going wrong with the foreach loop in btnAdd_Click Event....
Thanks..
You can't remove items from an enumeration while you are looping through it using a foreach, which is what the error message is trying to tell you.
Switching to a straight for loop will get your code to execute:
protected void btnAdd_Click(object sender, EventArgs e)
{
for(var i=0; i<lstMain.Items.Count; i++)
{
var list = lstMain.Items[i];
lstFAvourite.ClearSelection();
lstFAvourite.Items.Add(list);
lstMain.Items.Remove(list);
i--;
}
}
However, I believe this code will add all items from lstMain to lstFAvourite. I think perhaps that we should be looking at the Selected property of the ListItem as well in the for loop. For example:
protected void btnAdd_Click(object sender, EventArgs e)
{
for (var i = 0; i < lstMain.Items.Count; i++)
{
var list = lstMain.Items[i];
if(!list.Selected) continue;
lstFAvourite.ClearSelection();
lstFAvourite.Items.Add(list);
lstMain.Items.Remove(list);
//Decrement counter since we just removed an item
i--;
}
}
Another method.
lstMain.Items
.Cast<ListItem>()
.ToList()
.ForEach( item =>
{
if(item.Selected)
{
lstFAvourite.Items.Add(item);
lstMain.Items.Remove(item);
}
}
);
lstFAvourite.ClearSelection();
N.B: much slower than the for loop method.
If you try to remove list box items using a for loop using an increment (++) statement, eventually that loop will throw out of bounds error failing to finish removing all the items you want. Use decrement (--) instead.
The error Collection was modified; enumeration operation may not execute is because, while you are deleting the items from the list its affecting the sequence. You need to iterate the items in reverse order for this.
for (int i = lstMain.Items.Count; i > 0; i--)
{
ListItem list = lstMain.Items[i];
lstFAvourite.ClearSelection();
lstFAvourite.Items.Add(list);
lstMain.Items.Remove(list);
}

Error: foreach statement cannot operate on variables of type 'System.Web.UI.WebControls.ListItem'

I am trying to move multiple selected item from one ListBox to another ListBox using this code
protected void imgbtnMoveRightListBox_Click(object sender, ImageClickEventArgs e)
{
foreach (var item in lstboxSkill.SelectedItem)
{
lstBBoxSkill2.Items.Add(item);
}
}
but it shows an error
foreach statement cannot operate on variables of type
'System.Web.UI.WebControls.ListItem' because
'System.Web.UI.WebControls.ListItem' does not contain a public
definition for 'GetEnumerator'
I don't know why this error occured.
Please help me to fix it
Check this code.
protected void imgbtnMoveRightListBox_Click(object senderImageClickEventArge)
{
foreach (ListItem item in lstboxSkill.Items)
{
lstBBoxSkill2.Items.Add(item);
}
}
Please check this snap shot I have created and its working fine.
and the code behind code is given below:
protected void Page_Load(object sender, EventArgs e)
{
lstboxSkill.Items.Add("ASP.Net");
lstboxSkill.Items.Add("C#");
lstboxSkill.Items.Add("AJAX");
lstboxSkill.Items.Add("JavaScript");
lstboxSkill.Items.Add("HTML");
lstboxSkill.Items.Add("HTML5");
lstboxSkill.Items.Add("JQuery");
}
protected void imgbtnMoveRightListBox_Click(object sender, EventArgs e)
{
foreach (ListItem Item in lstboxSkill.Items)
{
if (Item.Selected == true)
{
lstBBoxSkill2.Items.Add(Item);
}
}
}
This is because the SelectedItem property returns only the item with the lowest index out of the list of items selected. You should change your code as
protected void imgbtnMoveRightListBox_Click(object sender, EventArgs e)
{
foreach (ListItem Item in lstboxSkill.Items)
{
if (Item.Selected == true)
{
lstBBoxSkill2.Items.Add(Item);
}
}
}
And set both listbox SelectionMode="Multiple".
Hope this will help you. Don't forget marked as answer
Thanks
Solomon S.
lstboxSkill.SelectedItem is a ListItem, which is neither an array nor an object collection that implements the System.Collections.IEnumerable<T> or System.Collections.Generic.IEnumerable<T> interface, so it's not possible to do foreach against it.
I think this is what you're looking for:
foreach (var item in lstboxSkill.Items)
{
if (item.Selected)
{
lstBBoxSkill2.Items.Add(item);
}
}
protected void imgbtnMoveRightListBox_Click(object sender, EventArgs e)
{
lbltxt.Visible = false;
if (ListBox1.SelectedIndex >= 0) // in this we are checking whether a single item is clicked.
{
for (int i = 0; i < ListBox1.Items.Count; i++) // we are looping through the list box items
{
if (ListBox1.Items[i].Selected) // finding the selected items
{
if (!arraylist1.Contains(ListBox1.Items[i]))
{
arraylist1.Add(ListBox1.Items[i]); //if found then adding those items to the array list
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
{
ListBox2.Items.Add(((ListItem)arraylist1[i])); // we are adding the array elements to the second list box
}
ListBox1.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
lbltxt.Visible = true;
lbltxt.Text = "Please select atleast one in Listbox1 to move";
}
}
Source

Search items in the listbox using index

I am doing a project that uses listbox, I can add items, delete items, update items but I can't search,
this is my code for search
string search = Person.listperson[listBox1.SelectedIndex].lastname;
foreach (String s in search)
{
if (s.Equals(textBox6.Text))
{
//show searched items
MessageBox.Show("Success!");
}
}
can you help me with this?
thanks :)
I have here a code for search,
But it does not apply in the button, how can I apply this on the button?
private void textBox6_TextChanged(object sender, EventArgs e)
{
int index = listBox1.FindString(this.textBox6.Text);
if (0 <= index)
{
listBox1.SelectedIndex = index;
}
}
Try something like this, add a click event to your button and put your code in it. This works for me.
private void button1_Click(object sender, EventArgs e)
{
int index = listBox1.FindString(textBox6.Text);
if (index > -1)
{
listBox1.SelectedIndex = index;
}
}
Not sure what you're trying to do exactly, but here's some samples.
Also, start giving variables useful names. If you come back to this code in a month you'll have no idea what's going on there or what textBox6 is.
To find a string (textBox6) in the entire listperson collection:
var list = Person.listperson.Where(p => p.lastname.Contains(textBox6.Text));
To check if a specific item in listperson has a partial textBox6 value:
var search = Person.listperson[listBox1.SelectedIndex].lastname;
bool success = search.Contains(textBox6.Text);
Or if you'd rather compare the values:
bool success = (search == textBox6.Text);
you can foreach char in a string
string s = "Blippy you";
foreach (char item in s)
{
}
but anywho. try Text.RegularExpressions for string matching.
private void button1_Click(object sender, System.EventArgs e)
{
if (listBox1.FindString("Your String in Textbox 6") != -1)
{
MessageBox.Show("Success!");
}
}

Categories

Resources