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

4
  • Is this asp.net or winforms? Commented Nov 7, 2012 at 10:23
  • @DaniloVulović: an ASP.NET ListBox has no content property. Commented Nov 7, 2012 at 10:26
  • There is no ListBoxItem in winforms! Commented Nov 7, 2012 at 10:27
  • 1
    to be specific, I'm writing a Windows 8 metro apps. I use C# and XAML. Commented Nov 7, 2012 at 10:28

3 Answers 3

40

Try this:

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

listbox.Items.Add(itm);

listbox is name for ListBox.

Sign up to request clarification or add additional context in comments.

Comments

1

You can do like that

ListBox1.Items.Insert(0,new ListItem("ITEM 1", "Value"))

1 Comment

not working, there is no ListItem in Windows 8 metro app with C# and XAML
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.