PDA

View Full Version : Adding text to Listbox at specific index



Coolmo
2009-07-27, 12:26 PM
I have a form with a listbox on it and I want to add a piece of text "AAA" to the listbox when I click a button. When the listbox.selectedindex = -1 (nothing selected) the text adds perfectly to the end of the list but now I want to be able to click an item in the list thus selecting a listbox index and then click the button to add "AAA" to the same index position I have selected. All the samples I've read merely state how to add an item to the listbox:

Listbox1.Items.Add (Textstring)

but nothing tells me how to add an item at a specific index in the list. Can someone give me a simple code snipet of how to do this?

Kerry Brown
2009-07-28, 04:18 AM
http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.objectcollection.insert.aspx

// kdub

Kerry Brown
2009-07-28, 08:21 AM
Perhaps something like :-


// Codehimbelonga kdub
private void button1_Click(object sender, EventArgs e)
{
string tbVal = (textBox1.Text);
if (String.IsNullOrEmpty(tbVal.Trim()) == false)
{
if (listBox1.SelectedIndices.Count > 0)
{
int selectedIndex = listBox1.SelectedIndices[0];
// if before selected
if (this.radioButton1.Checked)
{
listBox1.Items.Insert(selectedIndex, tbVal);
}
// if after selected
else if (this.radioButton2.Checked)
{
listBox1.Items.Insert((selectedIndex + 1), tbVal);
}
}
else
{
listBox1.Items.Add(tbVal);
}
}
}

Coolmo
2009-07-28, 05:23 PM
Ahhh, so it's INSERT instead of ADD. That's why it's so difficult to learn VB.NET because in VBA you can specify the index with the ADD method. I searched everywhere on the internet about how to ADD a piece of text to a listbox at a certain index and came up with nothing... and now I know why. Thanks for the code and the clues. It does what I want now.