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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Rajneesh RaiRank #1,902 · 777 reputationPosted Feb 27, 2013, 7:54 AM EST
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);
Satyapriya NayakRank #47 · 31.5K reputationPosted Feb 27, 2013, 8:06 AM EST
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);
}
}
}
}
Arun Kurmi96 reputationPosted Feb 27, 2013, 9:36 PM EST
VulpesRank #55 · 29.2K reputationPosted Feb 27, 2013, 11:54 PM EST
So, if the value of this property is not -1, it means that an item must be selected.