hi,
if i remove an item from index 2 inn listbox and there is no item at index 2 i. e. only 2 item in listbox in index 0 and 1.then there is an exception.how handle it.
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Rajneesh RaiPosted Feb 27, 2013, 12:54 PM
yes,if you try to remove item at index 2 (that does not exists)of listbox, you would get exception ArgumentOutOfRangeException. So keep item removal code in try catch block..
and check that the index exists or not in listbox i.e.
int index = index to remove;
if (index < lb.Items.Count)
lb.Items.RemoveAt(index);
VulpesPosted Feb 28, 2013, 4:54 AM
So, if the value of this property is not -1, it means that an item must be selected.
Arun KurmiPosted Feb 28, 2013, 2:36 AM
Satyapriya NayakPosted Feb 27, 2013, 1:06 PM
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication7
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
listBox1.Items.Add("a");
listBox1.Items.Add("a");
listBox1.Items.Add("c");
}
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
int i = 0;
i = listBox1.SelectedIndex;
listBox1.Items.RemoveAt(i);
}
}
}
}