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

Recommended Answers

All 2 Replies

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.