Share via


C# create dynamic List

Question

Wednesday, September 18, 2013 9:17 AM

Hi i would like to create a dynamic List in C#. my results is not the same everytime sometimes will be 20 results, 30 results, 34 results and etc. But i want to retrieve out the results stored is that possible? Basically my results is not constant i'm retrieving IP address in the subnet out. but I need to store the IP address in a List and retrieve out.

I declare my list on top and initialize where the results is retrieve shown here.

addIP = new List<string>(); addIP.Add(reply.Address.ToString()); < this will generate the results in the while loop till end of the ip address

i retrieve out using

public void retrieveAllIP()

{

for(int i=0;i<addIP.Count();i++)

{

Debug.WriteLine(addIP[i]);

}

but after doing the forloop it will only display the last ip address 

All replies (7)

Wednesday, September 18, 2013 10:13 AM ✅Answered | 1 vote

I have gone through the cocde. I think you need declare and creation of the list out side of the loop.

i.e    stop = true;
                    if (listResults.InvokeRequired == true)
                        this.listResults.Invoke((MethodInvoker)delegate()
                        {

                            ListViewItem item = new ListViewItem();

                            item.Text = reply.Address.ToString();
                          **  addIP = new List<string>();**
                            addIP.Add(reply.Address.ToString());
                            addIP.Add(deviceType);

the above code for list creates new list each time and your old conntens will be over written. hence you will get only last written item. hope this works.


Wednesday, September 18, 2013 11:39 AM ✅Answered | 1 vote

Hi,

If you are calling "DisplayReply(PingReply reply)"  method in a loop, then you should declare out side of this method, preferably in class data item delcaration.


Wednesday, September 18, 2013 9:30 AM

Please add the code you use to get the IPs

Also, it seems like you're adding only one address :

addIP = new List<string>(); addIP.Add(reply.Address.ToString()); < this will generate the results in the

Please remember to 'Mark as Answer' the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.


Wednesday, September 18, 2013 9:56 AM

Hi this is the part to ping and get ping resuts.. thanks!                                                                                       

  public void PingCompletedCallback(object sender, PingCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled)
                {
                    Debug.WriteLine("Ping Canceled.");

                    // Let the main thread resume. 
                    // UserToken is the AutoResetEvent object that the main thread 
                    // is waiting for.
                    ((AutoResetEvent)e.UserState).Set();
                }

                // If an error occurred, display the exception to the user.
                if (e.Error != null)
                {
                    Debug.WriteLine("Ping Failed!");
                    //this will print exception
                    Debug.WriteLine(e.Error.ToString());

                    // Let the main thread resume. 
                    ((AutoResetEvent)e.UserState).Set();
                }
                else
                {
                    PingReply reply = e.Reply;

                    DisplayReply(reply);

                    // Let the main thread resume.
                    ((AutoResetEvent)e.UserState).Set();

                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Exception " + ex.Message);
            }
        }
        public void DisplayReply(PingReply reply)
        {
            if (reply == null)
                return;

            //Console.WriteLine("Ping Status: {0}", reply.Status);

            else if (reply.Status == IPStatus.Success)
            {

                    stop = true;
                    if (listResults.InvokeRequired == true)
                        this.listResults.Invoke((MethodInvoker)delegate()
                        {

                            ListViewItem item = new ListViewItem();

                            item.Text = reply.Address.ToString();
                            addIP = new List<string>();
                            addIP.Add(reply.Address.ToString());
                            addIP.Add(deviceType);

                            //string[] row1 = { deviceType, temp,};

                            //Debug.WriteLine(reply.Address.ToString());
                            //Debug.WriteLine(deviceType);

                            //listResults.Items.Add(reply.Address.ToString()).SubItems.AddRange(row1);
                        });

            }
        }

        public long ToInt(string addr)
        {
            try
            {
                return (long)(uint)System.Net.IPAddress.NetworkToHostOrder(
                   (int)System.Net.IPAddress.Parse(addr).Address);
            }
            catch (Exception x)
            {
                MessageBox.Show("Empty or Incorrect IP address specify",
    "Note",
    MessageBoxButtons.OK,
    MessageBoxIcon.Exclamation,
    MessageBoxDefaultButton.Button1);

                return 0;
            }

        }
        public string ToAddr(long address)
        {
            return System.Net.IPAddress.Parse(address.ToString()).ToString();
        }
        public void scanLiveHosts(string ipFrom, string ipTo)
        {
            long from = ToInt(ipFrom);
            long to = ToInt(ipTo);

            while (from < to)
            {
                string address = ToAddr(from);
                sendAsyncPingPacket(address);
                from++;
            }

        }


Wednesday, September 18, 2013 10:16 AM

I think you're right Ravi, just remove that line and it should work.

Please remember to 'Mark as Answer' the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.


Wednesday, September 18, 2013 11:28 AM

Hi Ravi, thanks for the reply. i will try that later on but i have one question. Do you mean i need to create this  **addIP = new List<string>();  **outside else if (reply.Status == IPStatus.Success) or outside this method public void DisplayReply(PingReply reply) ? sorry im a newbie in programming! thanks!


Wednesday, September 18, 2013 12:16 PM

ok i will try it later thanks Ravi.