adding a ListBoxItem in a ListBox in C#?
Asked Answered
G

3

22

I know that:

String test = "test";
ListBox.Items.Add(test);

or

String test = "test";
int index = 1;
ListBox.Items.Insert(index, String);

adds the String in a ListBox, but I want to insert ListBoxItem, how to? previously I learn that

var contentToString = (String)ListBoxItem.Content;

simply converts ListBoxItem to String, but I couldn't do the opposite to convert String to ListBoxItem

Gq answered 7/11, 2012 at 10:22 Comment(4)
Is this asp.net or winforms?Gailgaile
@DaniloVulović: an ASP.NET ListBox has no content property.Mulcahy
There is no ListBoxItem in winforms!Gailgaile
to be specific, I'm writing a Windows 8 metro apps. I use C# and XAML.Gq
C
40

Try this:

ListBoxItem itm = new ListBoxItem();
itm.Content = "some text";

listbox.Items.Add(itm);

listbox is name for ListBox.

Calbert answered 7/11, 2012 at 10:35 Comment(0)
A
1

You can do like that

ListBox1.Items.Insert(0,new ListItem("ITEM 1", "Value"))
Allare answered 7/11, 2012 at 10:29 Comment(1)
not working, there is no ListItem in Windows 8 metro app with C# and XAMLGq
F
1

Your object will always be in a ListBoxItem, the ListBox will generate one for you if you don't add it explicitly. To get the ListBoxItem you use:

var listboxitem = (ListBoxItem)listbox.ItemContainerGenerator.ContainerFromItem(myItem);
Futhark answered 7/11, 2012 at 10:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.