How to copy items to Listbox

Is there a way of square

elements in listbox

then the output will go to anotherlistbox

For example, I added an item to listbox

using a loop

int items;
items=2;
do
{
    listbox1.items.add(items);
    items=items+2;
} while(items<20);

      

+3


source to share


6 answers


If you want to add items 4, 16, 36, ... 324

, you can get it with code:



for (int i = 2; i < 20; i += 2) 
  listbox1.Items.Add(i * i);

      

+3


source


Based on the image you posted in the comments on Abdelhamid's answer, it looks like you are trying to fill the items in the second list as a square version of your counterparts in the first list

foreach(var item in listBox1.Items)
{
    //Since you don't specify their type I presume they need parsing..
    int num;
    int.TryParse(item.ToString(), out num);
    listBox2.Items.Add(num * num);
}

      



If you tried to do this at the same time filling in the first file.

int items = 2;
do
{
    listbox1.Items.Add(items);
    listbox2.Items.Add(items * items);
    items += 2;
} while(items<20);

      

+2


source


Use ListBox

for display and for user interaction and perform logical operations independently of the list.

// Initialize
List<int> input = new List<int>();
for (int i = 2; i < 20; i += 2) {
    input.Add(i);
}

// Calculate
List<int> result = new List<int>();
for (int i = 0; i < input.Count; i++) {
    int value = input[i];
    result.Add(value * value);
}

// Display
listbox1.Items.AddRange(input);
listbox2.Items.AddRange(result);

      

The GUI logic (graphical user interface) should always be separated from the so-called business logic (in this case, calculating squares). List<int>

represent data in business logic (called a Model). They are printable and do not need casting or transformation and are independent of some controls. If you want to convert your example to a web page, some of the business logic will remain exactly the same where, since the display part will be completely different.

+1


source


What about

int items =2;
int items_sq;
do
{
    listBox1.Items.Add(items);
    items_sq=Math.Pow(items,2); //squares the items variable
    listBox2.Items.Add(items_sq);    
    items += 2;
} while(items<20);

      

+1


source


int items;
items=2;
do
{
    listbox1.items.add(items);
    items = Math.Pow(items, 2)
} while(items<20);

      

0


source


Try it...

int items;
items=2;
do
{
    listbox1.items.add(items);
    listbox2.items.add(items*items);
    items=items+2;
} while(items<20);

      

0


source







All Articles