Click here to Skip to main content
15,889,651 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
I have an Error when I write this code :

for (int i = 0; i < ListBox1.Items.Count - 1; i++)
{
  if (ListBox1.Items[i].Selected)
    TextBox1.Text = ListBox1.Items[i].Text;
}

return null;
Posted
Updated 10-Nov-10 19:45pm
v2
Comments
R. Erasmus 11-Nov-10 5:54am    
What error are you getting?
One error that I picked up is "ListBox1.Items.Count - 1" should be "ListBox1.Items.Count" as you're using a '<' operator.

Hi,
if you want to loop though selected items just use SelectedItems property of ListBox:


C#
for (int i = 0; i < this.listBox1.SelectedItems.Count; i++)
{
    textBox1.Text += listBox1.SelectedItems[i].ToString() + "\r\n";
}
 
Share this answer
 
Comments
Dalek Dave 11-Nov-10 3:50am    
Good Call.
Ankur\m/ 11-Nov-10 4:28am    
OP has never mentioned that he wants to loop through the selected items. Moreover if that would have been the case, his code would have been textBox1.Text += and not textBox1.Text =
Note '+=' and '=' difference.
BTW this is his second post for the same question. The original one has been answered here: http://www.codeproject.com/Answers/126467/How-to-read-selected.aspx
Kanasz Robert 11-Nov-10 5:54am    
Look at his code. He try to test, whether item is selected. Because of this I guess he want to loop though selected items.
Manfred Rudolf Bihy 29-Nov-10 8:52am    
I agree with Robert on this.Seems pretty clear from his code that he only wants the selected bits. My 5!
what error you got? paste the exception code here
 
Share this answer
 
Comments
Ankur\m/ 11-Nov-10 4:31am    
You should put that as a comment below the question instead of an answer.
I think you want to add the selected item of list box into the text box.for that

first initialise
TextBox1.Text=string.empty;


TextBox1.Text += ListBox1.Items[i].Text;

or
TextBox1.Text =TextBox1.Text+ ListBox1.Items[i].Text;
 
Share this answer
 
v2
Comments
Kanasz Robert 11-Nov-10 3:19am    
Hi, he wants to loop through selected items. In your answer base idea is missing. sorry.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900