0

hi all,

Am trying to create a structure with members ,creating an arraylist to get input from textbox so that it can bind in listbox. I am not geting the desired thind.Code attached .
Kindly help

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace WindowsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public struct MyStruct
        {
            public string name;
            public string data;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            ArrayList arr = new ArrayList();
            arr.Add(textBox2.Text);
            arr.Add(textBox1.Text);


            MyStruct[] array = new MyStruct [arr.Count];
            arr.CopyTo(array);

                    for (int i = 0; i < arr.Count; i++)
            {
                listBox1.Items.Add(array[i].name);


                listBox1.Items.Add(array[i].data);
            }


        }
    }
}

Am geting an error in copying arraylist to array then accessing it.
Kindly some one help

Edited by mike_2000_17: Fixed formatting

3
Contributors
2
Replies
4
Views
7 Years
Discussion Span
Last Post by Ionelul
0

I am not sure what you expect to happen.
Debugging shows the the ArrayList contains an array of String and the array you are copying to is an array of MyStruct.
There is a type conflict.
If you use a stronger typing such as List<string> instead of ArrayList this would be detected at compile time.

private void button1_Click(object sender, EventArgs e)
{
    List<string> arr = new List<string>(); //<--- changed from ArrayList
    arr.Add(textBox2.Text);
    arr.Add(textBox1.Text);

    MyStruct[] array = new MyStruct[arr.Count];
    arr.CopyTo(array); //<--- compile error here

    for (int i = 0; i < arr.Count; i++)
    {
        listBox1.Items.Add(array[i].name);


        listBox1.Items.Add(array[i].data);
    }
}

You will have to re-think your code.

0

Why don't you try to do a standard copy as below?

//  arr.CopyTo(array);
  for (int i = 0; i < arr.Count; i++)
      array[i].name = arr[i].toString();

Ionut

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.